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