r13590: * replace all pdb_init_sam[_talloc]() calls with samu_new()
[tprouty/samba.git] / source3 / utils / net_rpc_samsync.c
1 /* 
2    Unix SMB/CIFS implementation.
3    dump the remote SAM using rpc samsync operations
4
5    Copyright (C) Andrew Tridgell 2002
6    Copyright (C) Tim Potter 2001,2002
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2005
8    Modified by Volker Lendecke 2002
9    Copyright (C) Jeremy Allison 2005.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 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 struct samu_DELTA to a struct samu. */
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(struct samu *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         struct samu *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 ( !(sam_account = samu_new( NULL )) ) {
512                 return NT_STATUS_NO_MEMORY;
513         }
514
515         if (!(passwd = Get_Pwnam(account))) {
516                 /* Create appropriate user */
517                 if (delta->acb_info & ACB_NORMAL) {
518                         pstrcpy(add_script, lp_adduser_script());
519                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
520                             (delta->acb_info & ACB_SVRTRUST) ||
521                             (delta->acb_info & ACB_DOMTRUST) ) {
522                         pstrcpy(add_script, lp_addmachine_script());
523                 } else {
524                         DEBUG(1, ("Unknown user type: %s\n",
525                                   pdb_encode_acct_ctrl(delta->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
526                         nt_ret = NT_STATUS_UNSUCCESSFUL;
527                         goto done;
528                 }
529                 if (*add_script) {
530                         int add_ret;
531                         all_string_sub(add_script, "%u", account,
532                                        sizeof(account));
533                         add_ret = smbrun(add_script,NULL);
534                         DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
535                                  "gave %d\n", add_script, add_ret));
536                 }
537                 
538                 /* try and find the possible unix account again */
539                 if ( !(passwd = Get_Pwnam(account)) ) {
540                         d_fprintf(stderr, "Could not create posix account info for '%s'\n", account);
541                         nt_ret = NT_STATUS_NO_SUCH_USER;
542                         goto done;
543                 }
544         }
545         
546         sid_copy(&user_sid, get_global_sam_sid());
547         sid_append_rid(&user_sid, delta->user_rid);
548
549         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n", sid_to_string(sid_string, &user_sid), account));
550         if (!pdb_getsampwsid(sam_account, &user_sid)) {
551                 sam_account_from_delta(sam_account, delta);
552                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
553                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
554                 if (!NT_STATUS_IS_OK(pdb_add_sam_account(sam_account))) {
555                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
556                                   account));
557                         return NT_STATUS_ACCESS_DENIED; 
558                 }
559         } else {
560                 sam_account_from_delta(sam_account, delta);
561                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
562                           sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
563                 if (!NT_STATUS_IS_OK(pdb_update_sam_account(sam_account))) {
564                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
565                                   account));
566                         TALLOC_FREE(sam_account);
567                         return NT_STATUS_ACCESS_DENIED; 
568                 }
569         }
570
571         group_sid = *pdb_get_group_sid(sam_account);
572
573         if (!pdb_getgrsid(&map, group_sid)) {
574                 DEBUG(0, ("Primary group of %s has no mapping!\n",
575                           pdb_get_username(sam_account)));
576         } else {
577                 if (map.gid != passwd->pw_gid) {
578                         if (!(grp = getgrgid(map.gid))) {
579                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
580                                           (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_static(&group_sid)));
581                         } else {
582                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
583                         }
584                 }
585         }       
586
587         if ( !passwd ) {
588                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
589                         pdb_get_username(sam_account)));
590         }
591
592  done:
593         TALLOC_FREE(sam_account);
594         return nt_ret;
595 }
596
597 static NTSTATUS fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
598 {
599         fstring name;
600         fstring comment;
601         struct group *grp = NULL;
602         DOM_SID group_sid;
603         fstring sid_string;
604         GROUP_MAP map;
605         BOOL insert = True;
606
607         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name)-1);
608         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment)-1);
609
610         /* add the group to the mapping table */
611         sid_copy(&group_sid, get_global_sam_sid());
612         sid_append_rid(&group_sid, rid);
613         sid_to_string(sid_string, &group_sid);
614
615         if (pdb_getgrsid(&map, group_sid)) {
616                 if ( map.gid != -1 )
617                         grp = getgrgid(map.gid);
618                 insert = False;
619         }
620
621         if (grp == NULL) {
622                 gid_t gid;
623
624                 /* No group found from mapping, find it from its name. */
625                 if ((grp = getgrnam(name)) == NULL) {
626                 
627                         /* No appropriate group found, create one */
628                         
629                         d_printf("Creating unix group: '%s'\n", name);
630                         
631                         if (smb_create_group(name, &gid) != 0)
632                                 return NT_STATUS_ACCESS_DENIED;
633                                 
634                         if ((grp = getgrnam(name)) == NULL)
635                                 return NT_STATUS_ACCESS_DENIED;
636                 }
637         }
638
639         map.gid = grp->gr_gid;
640         map.sid = group_sid;
641         map.sid_name_use = SID_NAME_DOM_GRP;
642         fstrcpy(map.nt_name, name);
643         if (delta->hdr_grp_desc.buffer) {
644                 fstrcpy(map.comment, comment);
645         } else {
646                 fstrcpy(map.comment, "");
647         }
648
649         if (insert)
650                 pdb_add_group_mapping_entry(&map);
651         else
652                 pdb_update_group_mapping_entry(&map);
653
654         return NT_STATUS_OK;
655 }
656
657 static NTSTATUS fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
658 {
659         int i;
660         TALLOC_CTX *t = NULL;
661         char **nt_members = NULL;
662         char **unix_members;
663         DOM_SID group_sid;
664         GROUP_MAP map;
665         struct group *grp;
666
667         if (delta->num_members == 0) {
668                 return NT_STATUS_OK;
669         }
670
671         sid_copy(&group_sid, get_global_sam_sid());
672         sid_append_rid(&group_sid, rid);
673
674         if (!get_domain_group_from_sid(group_sid, &map)) {
675                 DEBUG(0, ("Could not find global group %d\n", rid));
676                 return NT_STATUS_NO_SUCH_GROUP;
677         }
678
679         if (!(grp = getgrgid(map.gid))) {
680                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
681                 return NT_STATUS_NO_SUCH_GROUP;
682         }
683
684         d_printf("Group members of %s: ", grp->gr_name);
685
686         if (!(t = talloc_init("fetch_group_mem_info"))) {
687                 DEBUG(0, ("could not talloc_init\n"));
688                 return NT_STATUS_NO_MEMORY;
689         }
690
691         nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
692
693         for (i=0; i<delta->num_members; i++) {
694                 struct samu *member = NULL;
695                 DOM_SID member_sid;
696
697                 if ( !(member = samu_new(t)) ) {
698                         talloc_destroy(t);
699                         return NT_STATUS_NO_MEMORY;
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                         TALLOC_FREE(member);
709                         continue;
710                 }
711
712                 if (pdb_get_group_rid(member) == rid) {
713                         d_printf("%s(primary),", pdb_get_username(member));
714                         TALLOC_FREE(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                 TALLOC_FREE(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         return NT_STATUS_OK;
839 }
840
841 static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
842 {
843         time_t u_max_age, u_min_age, u_logout, u_lockoutreset, u_lockouttime;
844         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
845         pstring domname;
846
847         u_max_age = nt_time_to_unix_abs((NTTIME *)&delta->max_pwd_age);
848         u_min_age = nt_time_to_unix_abs((NTTIME *)&delta->min_pwd_age);
849         u_logout = nt_time_to_unix_abs((NTTIME *)&delta->force_logoff);
850         u_lockoutreset = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.reset_count);
851         u_lockouttime = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.lockout_duration);
852
853         unistr2_to_ascii(domname, &delta->uni_dom_name, sizeof(domname) - 1);
854
855         /* we don't handle BUILTIN account policies */  
856         if (!strequal(domname, get_global_sam_name())) {
857                 printf("skipping SAM_DOMAIN_INFO delta for '%s' (is not my domain)\n", domname);
858                 return NT_STATUS_OK;
859         }
860
861
862         if (!pdb_set_account_policy(AP_PASSWORD_HISTORY, delta->pwd_history_len))
863                 return nt_status;
864
865         if (!pdb_set_account_policy(AP_MIN_PASSWORD_LEN, delta->min_pwd_len))
866                 return nt_status;
867
868         if (!pdb_set_account_policy(AP_MAX_PASSWORD_AGE, (uint32)u_max_age))
869                 return nt_status;
870
871         if (!pdb_set_account_policy(AP_MIN_PASSWORD_AGE, (uint32)u_min_age))
872                 return nt_status;
873
874         if (!pdb_set_account_policy(AP_TIME_TO_LOGOUT, (uint32)u_logout))
875                 return nt_status;
876
877         if (!pdb_set_account_policy(AP_BAD_ATTEMPT_LOCKOUT, delta->account_lockout.bad_attempt_lockout))
878                 return nt_status;
879
880         if (!pdb_set_account_policy(AP_RESET_COUNT_TIME, (uint32)u_lockoutreset/60))
881                 return nt_status;
882
883         if (u_lockouttime != -1)
884                 u_lockouttime /= 60;
885
886         if (!pdb_set_account_policy(AP_LOCK_ACCOUNT_DURATION, (uint32)u_lockouttime))
887                 return nt_status;
888
889         if (!pdb_set_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, delta->logon_chgpass))
890                 return nt_status;
891
892         return NT_STATUS_OK;
893 }
894
895
896 static void fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
897                 DOM_SID dom_sid)
898 {
899         switch(hdr_delta->type) {
900         case SAM_DELTA_ACCOUNT_INFO:
901                 fetch_account_info(hdr_delta->target_rid,
902                                    &delta->account_info);
903                 break;
904         case SAM_DELTA_GROUP_INFO:
905                 fetch_group_info(hdr_delta->target_rid,
906                                  &delta->group_info);
907                 break;
908         case SAM_DELTA_GROUP_MEM:
909                 fetch_group_mem_info(hdr_delta->target_rid,
910                                      &delta->grp_mem_info);
911                 break;
912         case SAM_DELTA_ALIAS_INFO:
913                 fetch_alias_info(hdr_delta->target_rid,
914                                  &delta->alias_info, dom_sid);
915                 break;
916         case SAM_DELTA_ALIAS_MEM:
917                 fetch_alias_mem(hdr_delta->target_rid,
918                                 &delta->als_mem_info, dom_sid);
919                 break;
920         case SAM_DELTA_DOMAIN_INFO:
921                 fetch_domain_info(hdr_delta->target_rid,
922                                 &delta->domain_info);
923                 break;
924         /* The following types are recognised but not handled */
925         case SAM_DELTA_RENAME_GROUP:
926                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
927                 break;
928         case SAM_DELTA_RENAME_USER:
929                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
930                 break;
931         case SAM_DELTA_RENAME_ALIAS:
932                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
933                 break;
934         case SAM_DELTA_POLICY_INFO:
935                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
936                 break;
937         case SAM_DELTA_TRUST_DOMS:
938                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
939                 break;
940         case SAM_DELTA_PRIVS_INFO:
941                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
942                 break;
943         case SAM_DELTA_SECRET_INFO:
944                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
945                 break;
946         case SAM_DELTA_DELETE_GROUP:
947                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
948                 break;
949         case SAM_DELTA_DELETE_USER:
950                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
951                 break;
952         case SAM_DELTA_MODIFIED_COUNT:
953                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
954                 break;
955         default:
956                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
957                 break;
958         }
959 }
960
961 static NTSTATUS fetch_database(struct rpc_pipe_client *pipe_hnd, uint32 db_type, DOM_SID dom_sid)
962 {
963         uint32 sync_context = 0;
964         NTSTATUS result;
965         int i;
966         TALLOC_CTX *mem_ctx;
967         SAM_DELTA_HDR *hdr_deltas;
968         SAM_DELTA_CTR *deltas;
969         uint32 num_deltas;
970
971         if (!(mem_ctx = talloc_init("fetch_database")))
972                 return NT_STATUS_NO_MEMORY;
973
974         switch( db_type ) {
975         case SAM_DATABASE_DOMAIN:
976                 d_printf("Fetching DOMAIN database\n");
977                 break;
978         case SAM_DATABASE_BUILTIN:
979                 d_printf("Fetching BUILTIN database\n");
980                 break;
981         case SAM_DATABASE_PRIVS:
982                 d_printf("Fetching PRIVS databases\n");
983                 break;
984         default:
985                 d_printf("Fetching unknown database type %u\n", db_type );
986                 break;
987         }
988
989         do {
990                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
991                                                db_type, sync_context,
992                                                &num_deltas,
993                                                &hdr_deltas, &deltas);
994
995                 if (NT_STATUS_IS_OK(result) ||
996                     NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
997                         for (i = 0; i < num_deltas; i++) {
998                                 fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
999                         }
1000                 } else
1001                         return result;
1002
1003                 sync_context += 1;
1004         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1005
1006         talloc_destroy(mem_ctx);
1007
1008         return result;
1009 }
1010
1011 static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const char 
1012                        *builtin_sid, FILE *add_fd)
1013 {
1014         char *user_suffix, *group_suffix, *machine_suffix, *idmap_suffix;
1015         char *user_attr=NULL, *group_attr=NULL;
1016         char *suffix_attr;
1017         int len;
1018
1019         /* Get the suffix attribute */
1020         suffix_attr = sstring_sub(suffix, '=', ',');
1021         if (suffix_attr == NULL) {
1022                 len = strlen(suffix);
1023                 suffix_attr = (char*)SMB_MALLOC(len+1);
1024                 memcpy(suffix_attr, suffix, len);
1025                 suffix_attr[len] = '\0';
1026         }
1027
1028         /* Write the base */
1029         fprintf(add_fd, "# %s\n", suffix);
1030         fprintf(add_fd, "dn: %s\n", suffix);
1031         fprintf(add_fd, "objectClass: dcObject\n");
1032         fprintf(add_fd, "objectClass: organization\n");
1033         fprintf(add_fd, "o: %s\n", suffix_attr);
1034         fprintf(add_fd, "dc: %s\n", suffix_attr);
1035         fprintf(add_fd, "\n");
1036         fflush(add_fd);
1037
1038         user_suffix = lp_ldap_user_suffix();
1039         /* If it exists and is distinct from other containers, 
1040            Write the Users entity */
1041         if (user_suffix && *user_suffix &&
1042             strcmp(user_suffix, suffix)) {
1043                 user_attr = sstring_sub(lp_ldap_user_suffix(), '=', ',');
1044                 fprintf(add_fd, "# %s\n", user_suffix);
1045                 fprintf(add_fd, "dn: %s\n", user_suffix);
1046                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1047                 fprintf(add_fd, "ou: %s\n", user_attr);
1048                 fprintf(add_fd, "\n");
1049                 fflush(add_fd);
1050         }
1051
1052
1053         group_suffix = lp_ldap_group_suffix();
1054         /* If it exists and is distinct from other containers, 
1055            Write the Groups entity */
1056         if (group_suffix && *group_suffix &&
1057             strcmp(group_suffix, suffix)) {
1058                 group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1059                 fprintf(add_fd, "# %s\n", group_suffix);
1060                 fprintf(add_fd, "dn: %s\n", group_suffix);
1061                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1062                 fprintf(add_fd, "ou: %s\n", group_attr);
1063                 fprintf(add_fd, "\n");
1064                 fflush(add_fd);
1065         }
1066
1067         /* If it exists and is distinct from other containers, 
1068            Write the Computers entity */
1069         machine_suffix = lp_ldap_machine_suffix();
1070         if (machine_suffix && *machine_suffix && 
1071             strcmp(machine_suffix, user_suffix) &&
1072             strcmp(machine_suffix, suffix)) {
1073                 fprintf(add_fd, "# %s\n", lp_ldap_machine_suffix());
1074                 fprintf(add_fd, "dn: %s\n", lp_ldap_machine_suffix());
1075                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1076                 fprintf(add_fd, "ou: %s\n", 
1077                         sstring_sub(lp_ldap_machine_suffix(), '=', ','));
1078                 fprintf(add_fd, "\n");
1079                 fflush(add_fd);
1080         }
1081
1082         /* If it exists and is distinct from other containers, 
1083            Write the IdMap entity */
1084         idmap_suffix = lp_ldap_idmap_suffix();
1085         if (idmap_suffix && *idmap_suffix &&
1086             strcmp(idmap_suffix, user_suffix) &&
1087             strcmp(idmap_suffix, suffix)) {
1088                 fprintf(add_fd, "# %s\n", idmap_suffix);
1089                 fprintf(add_fd, "dn: %s\n", idmap_suffix);
1090                 fprintf(add_fd, "ObjectClass: organizationalUnit\n");
1091                 fprintf(add_fd, "ou: %s\n", 
1092                         sstring_sub(lp_ldap_idmap_suffix(), '=', ','));
1093                 fprintf(add_fd, "\n");
1094                 fflush(add_fd);
1095         }
1096
1097         /* Write the root entity */
1098         fprintf(add_fd, "# root, %s, %s\n", user_attr, suffix);
1099         fprintf(add_fd, "dn: uid=root,ou=%s,%s\n", user_attr, suffix);
1100         fprintf(add_fd, "cn: root\n");
1101         fprintf(add_fd, "sn: root\n");
1102         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1103         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1104         fprintf(add_fd, "objectClass: posixAccount\n");
1105         fprintf(add_fd, "objectClass: shadowAccount\n");
1106         fprintf(add_fd, "gidNumber: 0\n");
1107         fprintf(add_fd, "uid: root\n");
1108         fprintf(add_fd, "uidNumber: 0\n");
1109         fprintf(add_fd, "homeDirectory: /home/root\n");
1110         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1111         fprintf(add_fd, "sambaLogonTime: 0\n");
1112         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1113         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1114         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1115         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1116         fprintf(add_fd, "sambaHomePath: \\\\PDC-SRV\root\n");
1117         fprintf(add_fd, "sambaHomeDrive: H:\n");
1118         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SRV\\profiles\\root\n");
1119         fprintf(add_fd, "sambaprimaryGroupSID: %s-512\n", sid);
1120         fprintf(add_fd, "sambaLMPassword: XXX\n");
1121         fprintf(add_fd, "sambaNTPassword: XXX\n");
1122         fprintf(add_fd, "sambaAcctFlags: [U\n");
1123         fprintf(add_fd, "sambaSID: %s-500\n", sid);
1124         fprintf(add_fd, "loginShell: /bin/false\n");
1125         fprintf(add_fd, "\n");
1126         fflush(add_fd);
1127
1128         /* Write the domain entity */
1129         fprintf(add_fd, "# %s, %s\n", lp_workgroup(), suffix);
1130         fprintf(add_fd, "dn: sambaDomainName=%s,%s\n", lp_workgroup(),
1131                 suffix);
1132         fprintf(add_fd, "objectClass: sambaDomain\n");
1133         fprintf(add_fd, "objectClass: sambaUnixIdPool\n");
1134         fprintf(add_fd, "sambaDomainName: %s\n", lp_workgroup());
1135         fprintf(add_fd, "sambaSID: %s\n", sid);
1136         fprintf(add_fd, "uidNumber: %d\n", ++ldif_uid);
1137         fprintf(add_fd, "gidNumber: %d\n", ++ldif_gid);
1138         fprintf(add_fd, "\n");
1139         fflush(add_fd);
1140
1141         /* Write user nobody entity */
1142         fprintf(add_fd, "# nobody, %s, %s\n", user_attr, suffix);
1143         fprintf(add_fd, "dn: uid=nobody,ou=%s,%s\n", user_attr, suffix);
1144         fprintf(add_fd, "cn: nobody\n");
1145         fprintf(add_fd, "sn: nobody\n");
1146         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1147         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1148         fprintf(add_fd, "objectClass: posixAccount\n");
1149         fprintf(add_fd, "objectClass: shadowAccount\n");
1150         fprintf(add_fd, "gidNumber: 514\n");
1151         fprintf(add_fd, "uid: nobody\n");
1152         fprintf(add_fd, "uidNumber: 999\n");
1153         fprintf(add_fd, "homeDirectory: /dev/null\n");
1154         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1155         fprintf(add_fd, "sambaLogonTime: 0\n");
1156         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1157         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1158         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1159         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1160         fprintf(add_fd, "sambaHomePath: \\\\PDC-SMD3\\homes\\nobody\n");
1161         fprintf(add_fd, "sambaHomeDrive: H:\n");
1162         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SMB3\\profiles\\nobody\n");
1163         fprintf(add_fd, "sambaprimaryGroupSID: %s-514\n", sid);
1164         fprintf(add_fd, "sambaLMPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1165         fprintf(add_fd, "sambaNTPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1166         fprintf(add_fd, "sambaAcctFlags: [NU\n");
1167         fprintf(add_fd, "sambaSID: %s-2998\n", sid);
1168         fprintf(add_fd, "loginShell: /bin/false\n");
1169         fprintf(add_fd, "\n");
1170         fflush(add_fd);
1171
1172         /* Write the Domain Admins entity */ 
1173         fprintf(add_fd, "# Domain Admins, %s, %s\n", group_attr,
1174                 suffix);
1175         fprintf(add_fd, "dn: cn=Domain Admins,ou=%s,%s\n", group_attr,
1176                 suffix);
1177         fprintf(add_fd, "objectClass: posixGroup\n");
1178         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1179         fprintf(add_fd, "cn: Domain Admins\n");
1180         fprintf(add_fd, "memberUid: Administrator\n");
1181         fprintf(add_fd, "description: Netbios Domain Administrators\n");
1182         fprintf(add_fd, "gidNumber: 512\n");
1183         fprintf(add_fd, "sambaSID: %s-512\n", sid);
1184         fprintf(add_fd, "sambaGroupType: 2\n");
1185         fprintf(add_fd, "displayName: Domain Admins\n");
1186         fprintf(add_fd, "\n");
1187         fflush(add_fd);
1188
1189         /* Write the Domain Users entity */ 
1190         fprintf(add_fd, "# Domain Users, %s, %s\n", group_attr,
1191                 suffix);
1192         fprintf(add_fd, "dn: cn=Domain Users,ou=%s,%s\n", group_attr,
1193                 suffix);
1194         fprintf(add_fd, "objectClass: posixGroup\n");
1195         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1196         fprintf(add_fd, "cn: Domain Users\n");
1197         fprintf(add_fd, "description: Netbios Domain Users\n");
1198         fprintf(add_fd, "gidNumber: 513\n");
1199         fprintf(add_fd, "sambaSID: %s-513\n", sid);
1200         fprintf(add_fd, "sambaGroupType: 2\n");
1201         fprintf(add_fd, "displayName: Domain Users\n");
1202         fprintf(add_fd, "\n");
1203         fflush(add_fd);
1204
1205         /* Write the Domain Guests entity */ 
1206         fprintf(add_fd, "# Domain Guests, %s, %s\n", group_attr,
1207                 suffix);
1208         fprintf(add_fd, "dn: cn=Domain Guests,ou=%s,%s\n", group_attr,
1209                 suffix);
1210         fprintf(add_fd, "objectClass: posixGroup\n");
1211         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1212         fprintf(add_fd, "cn: Domain Guests\n");
1213         fprintf(add_fd, "description: Netbios Domain Guests\n");
1214         fprintf(add_fd, "gidNumber: 514\n");
1215         fprintf(add_fd, "sambaSID: %s-514\n", sid);
1216         fprintf(add_fd, "sambaGroupType: 2\n");
1217         fprintf(add_fd, "displayName: Domain Guests\n");
1218         fprintf(add_fd, "\n");
1219         fflush(add_fd);
1220
1221         /* Write the Domain Computers entity */
1222         fprintf(add_fd, "# Domain Computers, %s, %s\n", group_attr,
1223                 suffix);
1224         fprintf(add_fd, "dn: cn=Domain Computers,ou=%s,%s\n",
1225                 group_attr, suffix);
1226         fprintf(add_fd, "objectClass: posixGroup\n");
1227         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1228         fprintf(add_fd, "gidNumber: 515\n");
1229         fprintf(add_fd, "cn: Domain Computers\n");
1230         fprintf(add_fd, "description: Netbios Domain Computers accounts\n");
1231         fprintf(add_fd, "sambaSID: %s-515\n", sid);
1232         fprintf(add_fd, "sambaGroupType: 2\n");
1233         fprintf(add_fd, "displayName: Domain Computers\n");
1234         fprintf(add_fd, "\n");
1235         fflush(add_fd);
1236
1237         /* Write the Admininistrators Groups entity */
1238         fprintf(add_fd, "# Administrators, %s, %s\n", group_attr,
1239                 suffix);
1240         fprintf(add_fd, "dn: cn=Administrators,ou=%s,%s\n", group_attr,
1241                 suffix);
1242         fprintf(add_fd, "objectClass: posixGroup\n");
1243         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1244         fprintf(add_fd, "gidNumber: 544\n");
1245         fprintf(add_fd, "cn: Administrators\n");
1246         fprintf(add_fd, "description: Netbios Domain Members can fully administer the computer/sambaDomainName\n");
1247         fprintf(add_fd, "sambaSID: %s-544\n", builtin_sid);
1248         fprintf(add_fd, "sambaGroupType: 5\n");
1249         fprintf(add_fd, "displayName: Administrators\n");
1250         fprintf(add_fd, "\n");
1251
1252         /* Write the Print Operator entity */
1253         fprintf(add_fd, "# Print Operators, %s, %s\n", group_attr,
1254                 suffix);
1255         fprintf(add_fd, "dn: cn=Print Operators,ou=%s,%s\n",
1256                 group_attr, suffix);
1257         fprintf(add_fd, "objectClass: posixGroup\n");
1258         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1259         fprintf(add_fd, "gidNumber: 550\n");
1260         fprintf(add_fd, "cn: Print Operators\n");
1261         fprintf(add_fd, "description: Netbios Domain Print Operators\n");
1262         fprintf(add_fd, "sambaSID: %s-550\n", builtin_sid);
1263         fprintf(add_fd, "sambaGroupType: 5\n");
1264         fprintf(add_fd, "displayName: Print Operators\n");
1265         fprintf(add_fd, "\n");
1266         fflush(add_fd);
1267
1268         /* Write the Backup Operators entity */
1269         fprintf(add_fd, "# Backup Operators, %s, %s\n", group_attr,
1270                 suffix);
1271         fprintf(add_fd, "dn: cn=Backup Operators,ou=%s,%s\n",
1272                 group_attr, suffix);
1273         fprintf(add_fd, "objectClass: posixGroup\n");
1274         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1275         fprintf(add_fd, "gidNumber: 551\n");
1276         fprintf(add_fd, "cn: Backup Operators\n");
1277         fprintf(add_fd, "description: Netbios Domain Members can bypass file security to back up files\n");
1278         fprintf(add_fd, "sambaSID: %s-551\n", builtin_sid);
1279         fprintf(add_fd, "sambaGroupType: 5\n");
1280         fprintf(add_fd, "displayName: Backup Operators\n");
1281         fprintf(add_fd, "\n");
1282         fflush(add_fd);
1283
1284         /* Write the Replicators entity */
1285         fprintf(add_fd, "# Replicators, %s, %s\n", group_attr, suffix);
1286         fprintf(add_fd, "dn: cn=Replicators,ou=%s,%s\n", group_attr,
1287                 suffix);
1288         fprintf(add_fd, "objectClass: posixGroup\n");
1289         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1290         fprintf(add_fd, "gidNumber: 552\n");
1291         fprintf(add_fd, "cn: Replicators\n");
1292         fprintf(add_fd, "description: Netbios Domain Supports file replication in a sambaDomainName\n");
1293         fprintf(add_fd, "sambaSID: %s-552\n", builtin_sid);
1294         fprintf(add_fd, "sambaGroupType: 5\n");
1295         fprintf(add_fd, "displayName: Replicators\n");
1296         fprintf(add_fd, "\n");
1297         fflush(add_fd);
1298
1299         /* Deallocate memory, and return */
1300         if (suffix_attr != NULL) SAFE_FREE(suffix_attr);
1301         return NT_STATUS_OK;
1302 }
1303
1304 static NTSTATUS map_populate_groups(GROUPMAP *groupmap, ACCOUNTMAP *accountmap, fstring sid, 
1305                     const char *suffix, const char *builtin_sid)
1306 {
1307         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1308
1309         /* Map the groups created by populate_ldap_for_ldif */
1310         groupmap[0].rid = 512;
1311         groupmap[0].gidNumber = 512;
1312         pstr_sprintf(groupmap[0].sambaSID, "%s-512", sid);
1313         pstr_sprintf(groupmap[0].group_dn, "cn=Domain Admins,ou=%s,%s", 
1314                      group_attr, suffix);
1315         accountmap[0].rid = 512;
1316         pstr_sprintf(accountmap[0].cn, "%s", "Domain Admins");
1317
1318         groupmap[1].rid = 513;
1319         groupmap[1].gidNumber = 513;
1320         pstr_sprintf(groupmap[1].sambaSID, "%s-513", sid);
1321         pstr_sprintf(groupmap[1].group_dn, "cn=Domain Users,ou=%s,%s", 
1322                      group_attr, suffix);
1323         accountmap[1].rid = 513;
1324         pstr_sprintf(accountmap[1].cn, "%s", "Domain Users");
1325
1326         groupmap[2].rid = 514;
1327         groupmap[2].gidNumber = 514;
1328         pstr_sprintf(groupmap[2].sambaSID, "%s-514", sid);
1329         pstr_sprintf(groupmap[2].group_dn, "cn=Domain Guests,ou=%s,%s", 
1330                      group_attr, suffix);
1331         accountmap[2].rid = 514;
1332         pstr_sprintf(accountmap[2].cn, "%s", "Domain Guests");
1333
1334         groupmap[3].rid = 515;
1335         groupmap[3].gidNumber = 515;
1336         pstr_sprintf(groupmap[3].sambaSID, "%s-515", sid);
1337         pstr_sprintf(groupmap[3].group_dn, "cn=Domain Computers,ou=%s,%s",
1338                      group_attr, suffix);
1339         accountmap[3].rid = 515;
1340         pstr_sprintf(accountmap[3].cn, "%s", "Domain Computers");
1341
1342         groupmap[4].rid = 544;
1343         groupmap[4].gidNumber = 544;
1344         pstr_sprintf(groupmap[4].sambaSID, "%s-544", builtin_sid);
1345         pstr_sprintf(groupmap[4].group_dn, "cn=Administrators,ou=%s,%s",
1346                      group_attr, suffix);
1347         accountmap[4].rid = 515;
1348         pstr_sprintf(accountmap[4].cn, "%s", "Administrators");
1349
1350         groupmap[5].rid = 550;
1351         groupmap[5].gidNumber = 550;
1352         pstr_sprintf(groupmap[5].sambaSID, "%s-550", builtin_sid);
1353         pstr_sprintf(groupmap[5].group_dn, "cn=Print Operators,ou=%s,%s",
1354                      group_attr, suffix);
1355         accountmap[5].rid = 550;
1356         pstr_sprintf(accountmap[5].cn, "%s", "Print Operators");
1357
1358         groupmap[6].rid = 551;
1359         groupmap[6].gidNumber = 551;
1360         pstr_sprintf(groupmap[6].sambaSID, "%s-551", builtin_sid);
1361         pstr_sprintf(groupmap[6].group_dn, "cn=Backup Operators,ou=%s,%s",
1362                      group_attr, suffix);
1363         accountmap[6].rid = 551;
1364         pstr_sprintf(accountmap[6].cn, "%s", "Backup Operators");
1365
1366         groupmap[7].rid = 552;
1367         groupmap[7].gidNumber = 552;
1368         pstr_sprintf(groupmap[7].sambaSID, "%s-552", builtin_sid);
1369         pstr_sprintf(groupmap[7].group_dn, "cn=Replicators,ou=%s,%s",
1370                      group_attr, suffix);
1371         accountmap[7].rid = 551;
1372         pstr_sprintf(accountmap[7].cn, "%s", "Replicators");
1373         return NT_STATUS_OK;
1374 }
1375
1376 static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1377                          FILE *add_fd, fstring sid, char *suffix)
1378 {
1379         fstring groupname;
1380         uint32 grouptype = 0, g_rid = 0;
1381         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1382
1383         /* Get the group name */
1384         unistr2_to_ascii(groupname, 
1385                          &(delta->group_info.uni_grp_name),
1386                          sizeof(groupname)-1);
1387
1388         /* Set up the group type (always 2 for group info) */
1389         grouptype = 2;
1390
1391         /* These groups are entered by populate_ldap_for_ldif */
1392         if (strcmp(groupname, "Domain Admins") == 0 ||
1393             strcmp(groupname, "Domain Users") == 0 ||
1394             strcmp(groupname, "Domain Guests") == 0 ||
1395             strcmp(groupname, "Domain Computers") == 0 ||
1396             strcmp(groupname, "Administrators") == 0 ||
1397             strcmp(groupname, "Print Operators") == 0 ||
1398             strcmp(groupname, "Backup Operators") == 0 ||
1399             strcmp(groupname, "Replicators") == 0) {
1400                 return NT_STATUS_OK;
1401         } else {
1402                 /* Increment the gid for the new group */
1403                 ldif_gid++;
1404         }
1405
1406         /* Map the group rid, gid, and dn */
1407         g_rid = delta->group_info.gid.g_rid;
1408         groupmap->rid = g_rid;
1409         groupmap->gidNumber = ldif_gid;
1410         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1411         pstr_sprintf(groupmap->group_dn, 
1412                      "cn=%s,ou=%s,%s", groupname, group_attr, suffix);
1413
1414         /* Write the data to the temporary add ldif file */
1415         fprintf(add_fd, "# %s, %s, %s\n", groupname, group_attr,
1416                 suffix);
1417         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", groupname, group_attr,
1418                 suffix);
1419         fprintf(add_fd, "objectClass: posixGroup\n");
1420         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1421         fprintf(add_fd, "cn: %s\n", groupname);
1422         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1423         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1424         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1425         fprintf(add_fd, "displayName: %s\n", groupname);
1426         fprintf(add_fd, "\n");
1427         fflush(add_fd);
1428
1429         /* Return */
1430         return NT_STATUS_OK;
1431 }
1432
1433 static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1434                            ACCOUNTMAP *accountmap, FILE *add_fd,
1435                            fstring sid, char *suffix, int alloced)
1436 {
1437         fstring username, homedir, logonscript, homedrive, homepath;
1438         fstring hex_nt_passwd, hex_lm_passwd;
1439         fstring description, fullname, sambaSID;
1440         uchar lm_passwd[16], nt_passwd[16];
1441         char *flags;
1442         const char *blank = "", *shell = "/bin/bash";
1443         const char* nopasswd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1444         static uchar zero_buf[16];
1445         uint32 rid = 0, group_rid = 0, gidNumber = 0;
1446         time_t unix_time;
1447         int i;
1448
1449         /* Get the username */
1450         unistr2_to_ascii(username, 
1451                          &(delta->account_info.uni_acct_name),
1452                          sizeof(username)-1);
1453
1454         /* Get the rid */
1455         rid = delta->account_info.user_rid;
1456
1457         /* Map the rid and username for group member info later */
1458         accountmap->rid = rid;
1459         pstr_sprintf(accountmap->cn, "%s", username);
1460
1461         /* Get the home directory */
1462         unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
1463                          sizeof(homedir)-1);
1464         if (strcmp(homedir, blank) == 0) {
1465                 pstr_sprintf(homedir, "/home/%s", username);
1466         } else {
1467                 strncpy(homepath, homedir, sizeof(homepath));
1468         }       
1469
1470         /* Get the logon script */
1471         unistr2_to_ascii(logonscript, &(delta->account_info.uni_logon_script),
1472                         sizeof(logonscript)-1);
1473
1474         /* Get the home drive */
1475         unistr2_to_ascii(homedrive, &(delta->account_info.uni_dir_drive),
1476                         sizeof(homedrive)-1);
1477
1478         /* Get the description */
1479         unistr2_to_ascii(description, &(delta->account_info.uni_acct_desc),
1480                          sizeof(description)-1);
1481         if (strcmp(description, blank) == 0) {
1482                 pstr_sprintf(description, "System User");
1483         }
1484
1485         /* Get the display name */
1486         unistr2_to_ascii(fullname, &(delta->account_info.uni_full_name),
1487                          sizeof(fullname)-1);
1488
1489         /* Get lm and nt password data */
1490         if (memcmp(delta->account_info.pass.buf_lm_pwd, zero_buf, 16) != 0) {
1491                 sam_pwd_hash(delta->account_info.user_rid, 
1492                              delta->account_info.pass.buf_lm_pwd, 
1493                              lm_passwd, 0);
1494                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, 
1495                               delta->account_info.acb_info);
1496         } else {
1497                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
1498         }
1499         if (memcmp(delta->account_info.pass.buf_nt_pwd, zero_buf, 16) != 0) {
1500                 sam_pwd_hash(delta->account_info.user_rid, 
1501                              delta->account_info.pass.buf_nt_pwd, 
1502                                      nt_passwd, 0);
1503                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, 
1504                               delta->account_info.acb_info);
1505         } else {
1506                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
1507         }
1508         unix_time = nt_time_to_unix(&(delta->account_info.pwd_last_set_time));
1509
1510         /* The nobody user is entered by populate_ldap_for_ldif */
1511         if (strcmp(username, "nobody") == 0) {
1512                 return NT_STATUS_OK;
1513         } else {
1514                 /* Increment the uid for the new user */
1515                 ldif_uid++;
1516         }
1517
1518         /* Set up group id and sambaSID for the user */
1519         group_rid = delta->account_info.group_rid;
1520         for (i=0; i<alloced; i++) {
1521                 if (groupmap[i].rid == group_rid) break;
1522         }
1523         if (i == alloced){
1524                 DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1525                           group_rid));
1526                 return NT_STATUS_UNSUCCESSFUL;
1527         }
1528         gidNumber = groupmap[i].gidNumber;
1529         pstr_sprintf(sambaSID, groupmap[i].sambaSID);
1530
1531         /* Set up sambaAcctFlags */
1532         flags = pdb_encode_acct_ctrl(delta->account_info.acb_info,
1533                                      NEW_PW_FORMAT_SPACE_PADDED_LEN);
1534
1535         /* Add the user to the temporary add ldif file */
1536         fprintf(add_fd, "# %s, %s, %s\n", username, 
1537                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1538         fprintf(add_fd, "dn: uid=%s,ou=%s,%s\n", username, 
1539                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1540         fprintf(add_fd, "ObjectClass: top\n");
1541         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1542         fprintf(add_fd, "objectClass: posixAccount\n");
1543         fprintf(add_fd, "objectClass: shadowAccount\n");
1544         fprintf(add_fd, "objectClass: sambaSamAccount\n");
1545         fprintf(add_fd, "cn: %s\n", username);
1546         fprintf(add_fd, "sn: %s\n", username);
1547         fprintf(add_fd, "uid: %s\n", username);
1548         fprintf(add_fd, "uidNumber: %d\n", ldif_uid);
1549         fprintf(add_fd, "gidNumber: %d\n", gidNumber);
1550         fprintf(add_fd, "homeDirectory: %s\n", homedir);
1551         if (strcmp(homepath, blank) != 0)
1552                 fprintf(add_fd, "SambaHomePath: %s\n", homepath);
1553         if (strcmp(homedrive, blank) != 0)
1554                 fprintf(add_fd, "SambaHomeDrive: %s\n", homedrive);
1555         if (strcmp(logonscript, blank) != 0)
1556                 fprintf(add_fd, "SambaLogonScript: %s\n", logonscript);
1557         fprintf(add_fd, "loginShell: %s\n", shell);
1558         fprintf(add_fd, "gecos: System User\n");
1559         fprintf(add_fd, "description: %s\n", description);
1560         fprintf(add_fd, "sambaSID: %s-%d\n", sid, rid);
1561         fprintf(add_fd, "sambaPrimaryGroupSID: %s\n", sambaSID);
1562         if(strcmp(fullname, blank) != 0)
1563                 fprintf(add_fd, "displayName: %s\n", fullname);
1564         if (strcmp(nopasswd, hex_lm_passwd) != 0)
1565                 fprintf(add_fd, "sambaLMPassword: %s\n", hex_lm_passwd);
1566         if (strcmp(nopasswd, hex_nt_passwd) != 0)
1567                 fprintf(add_fd, "sambaNTPassword: %s\n", hex_nt_passwd);
1568         fprintf(add_fd, "sambaPwdLastSet: %d\n", (int)unix_time);
1569         fprintf(add_fd, "sambaAcctFlags: %s\n", flags);
1570         fprintf(add_fd, "\n");
1571         fflush(add_fd);
1572
1573         /* Return */
1574         return NT_STATUS_OK;
1575 }
1576
1577 static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1578                          FILE *add_fd, fstring sid, char *suffix, 
1579                          unsigned db_type)
1580 {
1581         fstring aliasname, description;
1582         uint32 grouptype = 0, g_rid = 0;
1583         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1584
1585         /* Get the alias name */
1586         unistr2_to_ascii(aliasname, &(delta->alias_info.uni_als_name),
1587                          sizeof(aliasname)-1);
1588
1589         /* Get the alias description */
1590         unistr2_to_ascii(description, &(delta->alias_info.uni_als_desc),
1591                          sizeof(description)-1);
1592
1593         /* Set up the group type */
1594         switch (db_type) {
1595                 case SAM_DATABASE_DOMAIN:
1596                         grouptype = 4;
1597                         break;
1598                 case SAM_DATABASE_BUILTIN:
1599                         grouptype = 5;
1600                         break;
1601                 default:
1602                         grouptype = 4;
1603                         break;
1604         }
1605
1606         /*
1607         These groups are entered by populate_ldap_for_ldif
1608         Note that populate creates a group called Relicators, 
1609         but NT returns a group called Replicator
1610         */
1611         if (strcmp(aliasname, "Domain Admins") == 0 ||
1612             strcmp(aliasname, "Domain Users") == 0 ||
1613             strcmp(aliasname, "Domain Guests") == 0 ||
1614             strcmp(aliasname, "Domain Computers") == 0 ||
1615             strcmp(aliasname, "Administrators") == 0 ||
1616             strcmp(aliasname, "Print Operators") == 0 ||
1617             strcmp(aliasname, "Backup Operators") == 0 ||
1618             strcmp(aliasname, "Replicator") == 0) {
1619                 return NT_STATUS_OK;
1620         } else {
1621                 /* Increment the gid for the new group */
1622                 ldif_gid++;
1623         }
1624
1625         /* Map the group rid and gid */
1626         g_rid = delta->group_info.gid.g_rid;
1627         groupmap->gidNumber = ldif_gid;
1628         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1629
1630         /* Write the data to the temporary add ldif file */
1631         fprintf(add_fd, "# %s, %s, %s\n", aliasname, group_attr,
1632                 suffix);
1633         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", aliasname, group_attr,
1634                 suffix);
1635         fprintf(add_fd, "objectClass: posixGroup\n");
1636         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1637         fprintf(add_fd, "cn: %s\n", aliasname);
1638         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1639         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1640         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1641         fprintf(add_fd, "displayName: %s\n", aliasname);
1642         fprintf(add_fd, "description: %s\n", description);
1643         fprintf(add_fd, "\n");
1644         fflush(add_fd);
1645
1646         /* Return */
1647         return NT_STATUS_OK;
1648 }
1649
1650 static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR *hdr_delta,
1651                             GROUPMAP *groupmap, ACCOUNTMAP *accountmap, 
1652                             FILE *mod_fd, int alloced)
1653 {
1654         fstring group_dn;
1655         uint32 group_rid = 0, rid = 0;
1656         int i, j, k;
1657
1658         /* Get the dn for the group */
1659         if (delta->grp_mem_info.num_members > 0) {
1660                 group_rid = hdr_delta->target_rid;
1661                 for (j=0; j<alloced; j++) {
1662                         if (groupmap[j].rid == group_rid) break;
1663                 }
1664                 if (j == alloced){
1665                         DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1666                                   group_rid));
1667                         return NT_STATUS_UNSUCCESSFUL;
1668                 }
1669                 pstr_sprintf(group_dn, "%s", groupmap[j].group_dn);
1670                 fprintf(mod_fd, "dn: %s\n", group_dn);
1671
1672                 /* Get the cn for each member */
1673                 for (i=0; i<delta->grp_mem_info.num_members; i++) {
1674                         rid = delta->grp_mem_info.rids[i];
1675                         for (k=0; k<alloced; k++) {
1676                                 if (accountmap[k].rid == rid) break;
1677                         }
1678                         if (k == alloced){
1679                                 DEBUG(1, ("Could not find rid %d in accountmap array\n", rid));
1680                                 return NT_STATUS_UNSUCCESSFUL;
1681                         }
1682                         fprintf(mod_fd, "memberUid: %s\n", accountmap[k].cn);
1683                 }
1684                 fprintf(mod_fd, "\n");
1685         }
1686         fflush(mod_fd);
1687
1688         /* Return */
1689         return NT_STATUS_OK;
1690 }
1691
1692 static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
1693                                         uint32 db_type,
1694                                         DOM_SID dom_sid,
1695                                         const char *user_file)
1696 {
1697         char *suffix;
1698         const char *builtin_sid = "S-1-5-32";
1699         char *ldif_file;
1700         fstring sid, domainname;
1701         uint32 sync_context = 0;
1702         NTSTATUS result;
1703         int k;
1704         TALLOC_CTX *mem_ctx;
1705         SAM_DELTA_HDR *hdr_deltas;
1706         SAM_DELTA_CTR *deltas;
1707         uint32 num_deltas;
1708         const char *add_ldif = "/tmp/add.ldif", *mod_ldif = "/tmp/mod.ldif";
1709         FILE *add_fd, *mod_fd, *ldif_fd;
1710         char sys_cmd[1024];
1711         int num_alloced = 0, g_index = 0, a_index = 0, sys_cmd_result;
1712
1713         /* Set up array for mapping accounts to groups */
1714         /* Array element is the group rid */
1715         GROUPMAP *groupmap = NULL;
1716
1717         /* Set up array for mapping account rid's to cn's */
1718         /* Array element is the account rid */
1719         ACCOUNTMAP *accountmap = NULL; 
1720
1721         if (!(mem_ctx = talloc_init("fetch_database"))) {
1722                 return NT_STATUS_NO_MEMORY;
1723         }
1724
1725         /* Ensure we have an output file */
1726         if (user_file)
1727                 ldif_file = talloc_strdup(mem_ctx, user_file);
1728         else
1729                 ldif_file = talloc_strdup(mem_ctx, "/tmp/tmp.ldif");
1730         
1731         if (ldif_file == NULL)
1732                 return NT_STATUS_NO_MEMORY;
1733
1734         /* Open the add and mod ldif files */
1735         add_fd = fopen(add_ldif, "a");
1736         mod_fd = fopen(mod_ldif, "a");
1737         if (add_fd == NULL || mod_fd == NULL) {
1738                 DEBUG(1, ("Could not open %s\n", add_ldif));
1739                 return NT_STATUS_UNSUCCESSFUL;
1740         } 
1741
1742         /* Open the user's ldif file */
1743         ldif_fd = fopen(ldif_file, "a");
1744         if (ldif_fd == NULL) {
1745                 DEBUG(1, ("Could not open %s\n", ldif_file));
1746                 return NT_STATUS_UNSUCCESSFUL;
1747         }
1748
1749         /* Get the sid */
1750         sid_to_string(sid, &dom_sid);
1751
1752         /* Get the ldap suffix */
1753         suffix = lp_ldap_suffix();
1754         if (suffix == NULL || strcmp(suffix, "") == 0) {
1755                 DEBUG(0,("ldap suffix missing from smb.conf--exiting\n"));
1756                 exit(1);
1757         }
1758
1759         /* Get other smb.conf data */
1760         if (!(lp_workgroup()) || !*(lp_workgroup())) {
1761                 DEBUG(0,("workgroup missing from smb.conf--exiting\n"));
1762                 exit(1);
1763         }
1764
1765         /* Allocate initial memory for groupmap and accountmap arrays */
1766         if (init_ldap == 1) {
1767                 groupmap = SMB_MALLOC_ARRAY(GROUPMAP, 8);
1768                 accountmap = SMB_MALLOC_ARRAY(ACCOUNTMAP, 8);
1769                 if (groupmap == NULL || accountmap == NULL) {
1770                         DEBUG(1,("GROUPMAP malloc failed\n"));
1771                         return NT_STATUS_NO_MEMORY;
1772                 }
1773
1774                 /* Initialize the arrays */
1775                 memset(groupmap, 0, sizeof(GROUPMAP)*8);
1776                 memset(accountmap, 0, sizeof(ACCOUNTMAP)*8);
1777
1778                 /* Remember how many we malloced */
1779                 num_alloced = 8;
1780
1781                 /* Initial database population */
1782                 populate_ldap_for_ldif(sid, suffix, builtin_sid, add_fd);
1783                 map_populate_groups(groupmap, accountmap, sid, suffix,
1784                             builtin_sid);
1785
1786                 /* Don't do this again */
1787                 init_ldap = 0;
1788         }
1789
1790         /* Announce what we are doing */
1791         switch( db_type ) {
1792                 case SAM_DATABASE_DOMAIN:
1793                         d_printf("Fetching DOMAIN database\n");
1794                         break;
1795                 case SAM_DATABASE_BUILTIN:
1796                         d_printf("Fetching BUILTIN database\n");
1797                         break;
1798                 case SAM_DATABASE_PRIVS:
1799                         d_printf("Fetching PRIVS databases\n");
1800                         break;
1801                 default:
1802                         d_printf("Fetching unknown database type %u\n", db_type );
1803                         break;
1804         }
1805
1806         do {
1807                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
1808                                                db_type, sync_context,
1809                                                &num_deltas, &hdr_deltas, 
1810                                                &deltas);
1811                 if (!NT_STATUS_IS_OK(result) &&
1812                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1813                         return NT_STATUS_OK;
1814                 }
1815
1816                 /* Re-allocate memory for groupmap and accountmap arrays */
1817                 groupmap = SMB_REALLOC_ARRAY(groupmap, GROUPMAP,
1818                                         num_deltas+num_alloced);
1819                 accountmap = SMB_REALLOC_ARRAY(accountmap, ACCOUNTMAP,
1820                                         num_deltas+num_alloced);
1821                 if (groupmap == NULL || accountmap == NULL) {
1822                         DEBUG(1,("GROUPMAP malloc failed\n"));
1823                         return NT_STATUS_NO_MEMORY;
1824                 }
1825
1826                 /* Initialize the new records */
1827                 memset(&groupmap[num_alloced], 0, 
1828                        sizeof(GROUPMAP)*num_deltas);
1829                 memset(&accountmap[num_alloced], 0,
1830                        sizeof(ACCOUNTMAP)*num_deltas);
1831
1832                 /* Remember how many we alloced this time */
1833                 num_alloced += num_deltas;
1834
1835                 /* Loop through the deltas */
1836                 for (k=0; k<num_deltas; k++) {
1837                         switch(hdr_deltas[k].type) {
1838                                 case SAM_DELTA_DOMAIN_INFO:
1839                                         /* Is this case needed? */
1840                                         unistr2_to_ascii(domainname, 
1841                                         &deltas[k].domain_info.uni_dom_name,
1842                                                 sizeof(domainname)-1);
1843                                         break;
1844
1845                                 case SAM_DELTA_GROUP_INFO:
1846                                         fetch_group_info_to_ldif(
1847                                                 &deltas[k], &groupmap[g_index],
1848                                                 add_fd, sid, suffix);
1849                                         g_index++;
1850                                         break;
1851
1852                                 case SAM_DELTA_ACCOUNT_INFO:
1853                                         fetch_account_info_to_ldif(
1854                                                 &deltas[k], groupmap, 
1855                                                 &accountmap[a_index], add_fd,
1856                                                 sid, suffix, num_alloced);
1857                                         a_index++;
1858                                         break;
1859
1860                                 case SAM_DELTA_ALIAS_INFO:
1861                                         fetch_alias_info_to_ldif(
1862                                                 &deltas[k], &groupmap[g_index],
1863                                                 add_fd, sid, suffix, db_type);
1864                                         g_index++;
1865                                         break;
1866
1867                                 case SAM_DELTA_GROUP_MEM:
1868                                         fetch_groupmem_info_to_ldif(
1869                                                 &deltas[k], &hdr_deltas[k], 
1870                                                 groupmap, accountmap, 
1871                                                 mod_fd, num_alloced);
1872                                         break;
1873
1874                                 case SAM_DELTA_ALIAS_MEM:
1875                                         break;
1876                                 case SAM_DELTA_POLICY_INFO:
1877                                         break;
1878                                 case SAM_DELTA_PRIVS_INFO:
1879                                         break;
1880                                 case SAM_DELTA_TRUST_DOMS:
1881                                         /* Implemented but broken */
1882                                         break;
1883                                 case SAM_DELTA_SECRET_INFO:
1884                                         /* Implemented but broken */
1885                                         break;
1886                                 case SAM_DELTA_RENAME_GROUP:
1887                                         /* Not yet implemented */
1888                                         break;
1889                                 case SAM_DELTA_RENAME_USER:
1890                                         /* Not yet implemented */
1891                                         break;
1892                                 case SAM_DELTA_RENAME_ALIAS:
1893                                         /* Not yet implemented */
1894                                         break;
1895                                 case SAM_DELTA_DELETE_GROUP:
1896                                         /* Not yet implemented */
1897                                         break;
1898                                 case SAM_DELTA_DELETE_USER:
1899                                         /* Not yet implemented */
1900                                         break;
1901                                 case SAM_DELTA_MODIFIED_COUNT:
1902                                         break;
1903                                 default:
1904                                 break;
1905                         } /* end of switch */
1906                 } /* end of for loop */
1907
1908                 /* Increment sync_context */
1909                 sync_context += 1;
1910
1911         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1912
1913         /* Close the ldif files */
1914         fclose(add_fd);
1915         fclose(mod_fd);
1916
1917         /* Write ldif data to the user's file */
1918         if (db_type == SAM_DATABASE_DOMAIN) {
1919                 fprintf(ldif_fd,
1920                         "# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
1921                 fprintf(ldif_fd,
1922                         "# =================================\n\n");
1923                 fflush(ldif_fd);
1924         } else if (db_type == SAM_DATABASE_BUILTIN) {
1925                 fprintf(ldif_fd,
1926                         "# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
1927                 fprintf(ldif_fd,
1928                         "# ==================================\n\n");
1929                 fflush(ldif_fd);
1930         }
1931         pstr_sprintf(sys_cmd, "cat %s >> %s", add_ldif, ldif_file);
1932         sys_cmd_result = system(sys_cmd);
1933         if (sys_cmd_result) {
1934                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1935                         sys_cmd, strerror(errno));
1936                 return NT_STATUS_UNSUCCESSFUL;
1937         }
1938         if (db_type == SAM_DATABASE_DOMAIN) {
1939                 fprintf(ldif_fd,
1940                         "# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
1941                 fprintf(ldif_fd,
1942                         "# ====================================\n\n");
1943                 fflush(ldif_fd);
1944         } else if (db_type == SAM_DATABASE_BUILTIN) {
1945                 fprintf(ldif_fd,
1946                         "# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
1947                 fprintf(ldif_fd,
1948                         "# =====================================\n\n");
1949                 fflush(ldif_fd);
1950         }
1951         pstr_sprintf(sys_cmd, "cat %s >> %s", mod_ldif, ldif_file);
1952         sys_cmd_result = system(sys_cmd);
1953         if (sys_cmd_result) {
1954                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1955                         sys_cmd, strerror(errno));
1956                 return NT_STATUS_UNSUCCESSFUL;
1957         }
1958
1959         /* Delete the temporary ldif files */
1960         pstr_sprintf(sys_cmd, "rm -f %s %s", add_ldif, mod_ldif);
1961         sys_cmd_result = system(sys_cmd);
1962         if (sys_cmd_result) {
1963                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1964                         sys_cmd, strerror(errno));
1965                 return NT_STATUS_UNSUCCESSFUL;
1966         }
1967
1968         /* Close the ldif file */
1969         fclose(ldif_fd);
1970
1971         /* Deallocate memory for the mapping arrays */
1972         SAFE_FREE(groupmap);
1973         SAFE_FREE(accountmap);
1974
1975         /* Return */
1976         talloc_destroy(mem_ctx);
1977         return NT_STATUS_OK;
1978 }
1979
1980 /** 
1981  * Basic usage function for 'net rpc vampire'
1982  * @param argc  Standard main() style argc
1983  * @param argc  Standard main() style argv.  Initial components are already
1984  *              stripped
1985  **/
1986
1987 int rpc_vampire_usage(int argc, const char **argv) 
1988 {       
1989         d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"\
1990                  "\t to pull accounts from a remote PDC where we are a BDC\n"\
1991                  "\t\t no args puts accounts in local passdb from smb.conf\n"\
1992                  "\t\t ldif - put accounts in ldif format (file defaults to /tmp/tmp.ldif\n");
1993
1994         net_common_flags_usage(argc, argv);
1995         return -1;
1996 }
1997
1998
1999 /* dump sam database via samsync rpc calls */
2000 NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
2001                                 const char *domain_name, 
2002                                 struct cli_state *cli,
2003                                 struct rpc_pipe_client *pipe_hnd,
2004                                 TALLOC_CTX *mem_ctx, 
2005                                 int argc,
2006                                 const char **argv) 
2007 {
2008         NTSTATUS result;
2009         fstring my_dom_sid_str;
2010         fstring rem_dom_sid_str;
2011
2012         if (!sid_equal(domain_sid, get_global_sam_sid())) {
2013                 d_printf("Cannot import users from %s at this time, "
2014                          "as the current domain:\n\t%s: %s\nconflicts "
2015                          "with the remote domain\n\t%s: %s\n"
2016                          "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
2017                          domain_name,
2018                          get_global_sam_name(), sid_to_string(my_dom_sid_str, 
2019                                                               get_global_sam_sid()),
2020                          domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
2021                          domain_name);
2022                 return NT_STATUS_UNSUCCESSFUL;
2023         }
2024
2025         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2026                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_DOMAIN,
2027                                         *domain_sid, argv[1]);
2028         } else {
2029                 result = fetch_database(pipe_hnd, SAM_DATABASE_DOMAIN, *domain_sid);
2030         }
2031
2032         if (!NT_STATUS_IS_OK(result)) {
2033                 d_fprintf(stderr, "Failed to fetch domain database: %s\n",
2034                          nt_errstr(result));
2035                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
2036                         d_fprintf(stderr, "Perhaps %s is a Windows 2000 native "
2037                                  "mode domain?\n", domain_name);
2038                 goto fail;
2039         }
2040
2041         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2042                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_BUILTIN, 
2043                                         global_sid_Builtin, argv[1]);
2044         } else {
2045                 result = fetch_database(pipe_hnd, SAM_DATABASE_BUILTIN, global_sid_Builtin);
2046         }
2047
2048         if (!NT_STATUS_IS_OK(result)) {
2049                 d_fprintf(stderr, "Failed to fetch builtin database: %s\n",
2050                          nt_errstr(result));
2051                 goto fail;
2052         }
2053
2054         /* Currently we crash on PRIVS somewhere in unmarshalling */
2055         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
2056
2057 fail:
2058         return result;
2059 }