r14053: Implement Simo's suggestion: don't use /dev/null for a 'bad' path for
[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                 fprintf(add_fd, "# %s\n", lp_ldap_machine_suffix());
1080                 fprintf(add_fd, "dn: %s\n", lp_ldap_machine_suffix());
1081                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1082                 fprintf(add_fd, "ou: %s\n", 
1083                         sstring_sub(lp_ldap_machine_suffix(), '=', ','));
1084                 fprintf(add_fd, "\n");
1085                 fflush(add_fd);
1086         }
1087
1088         /* If it exists and is distinct from other containers, 
1089            Write the IdMap entity */
1090         idmap_suffix = lp_ldap_idmap_suffix();
1091         if (idmap_suffix && *idmap_suffix &&
1092             strcmp(idmap_suffix, user_suffix) &&
1093             strcmp(idmap_suffix, suffix)) {
1094                 char *s;
1095                 fprintf(add_fd, "# %s\n", idmap_suffix);
1096                 fprintf(add_fd, "dn: %s\n", idmap_suffix);
1097                 fprintf(add_fd, "ObjectClass: organizationalUnit\n");
1098                 s = sstring_sub(lp_ldap_idmap_suffix(), '=', ',');
1099                 fprintf(add_fd, "ou: %s\n", s);
1100                 SAFE_FREE(s);
1101                 fprintf(add_fd, "\n");
1102                 fflush(add_fd);
1103         }
1104
1105         /* Write the root entity */
1106         fprintf(add_fd, "# root, %s, %s\n", user_attr, suffix);
1107         fprintf(add_fd, "dn: uid=root,ou=%s,%s\n", user_attr, suffix);
1108         fprintf(add_fd, "cn: root\n");
1109         fprintf(add_fd, "sn: root\n");
1110         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1111         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1112         fprintf(add_fd, "objectClass: posixAccount\n");
1113         fprintf(add_fd, "objectClass: shadowAccount\n");
1114         fprintf(add_fd, "gidNumber: 0\n");
1115         fprintf(add_fd, "uid: root\n");
1116         fprintf(add_fd, "uidNumber: 0\n");
1117         fprintf(add_fd, "homeDirectory: /home/root\n");
1118         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1119         fprintf(add_fd, "sambaLogonTime: 0\n");
1120         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1121         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1122         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1123         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1124         fprintf(add_fd, "sambaHomePath: \\\\PDC-SRV\root\n");
1125         fprintf(add_fd, "sambaHomeDrive: H:\n");
1126         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SRV\\profiles\\root\n");
1127         fprintf(add_fd, "sambaprimaryGroupSID: %s-512\n", sid);
1128         fprintf(add_fd, "sambaLMPassword: XXX\n");
1129         fprintf(add_fd, "sambaNTPassword: XXX\n");
1130         fprintf(add_fd, "sambaAcctFlags: [U\n");
1131         fprintf(add_fd, "sambaSID: %s-500\n", sid);
1132         fprintf(add_fd, "loginShell: /bin/false\n");
1133         fprintf(add_fd, "\n");
1134         fflush(add_fd);
1135
1136         /* Write the domain entity */
1137         fprintf(add_fd, "# %s, %s\n", lp_workgroup(), suffix);
1138         fprintf(add_fd, "dn: sambaDomainName=%s,%s\n", lp_workgroup(),
1139                 suffix);
1140         fprintf(add_fd, "objectClass: sambaDomain\n");
1141         fprintf(add_fd, "objectClass: sambaUnixIdPool\n");
1142         fprintf(add_fd, "sambaDomainName: %s\n", lp_workgroup());
1143         fprintf(add_fd, "sambaSID: %s\n", sid);
1144         fprintf(add_fd, "uidNumber: %d\n", ++ldif_uid);
1145         fprintf(add_fd, "gidNumber: %d\n", ++ldif_gid);
1146         fprintf(add_fd, "\n");
1147         fflush(add_fd);
1148
1149         /* Write user nobody entity */
1150         fprintf(add_fd, "# nobody, %s, %s\n", user_attr, suffix);
1151         fprintf(add_fd, "dn: uid=nobody,ou=%s,%s\n", user_attr, suffix);
1152         fprintf(add_fd, "cn: nobody\n");
1153         fprintf(add_fd, "sn: nobody\n");
1154         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1155         fprintf(add_fd, "objectClass: sambaSAMAccount\n");
1156         fprintf(add_fd, "objectClass: posixAccount\n");
1157         fprintf(add_fd, "objectClass: shadowAccount\n");
1158         fprintf(add_fd, "gidNumber: 514\n");
1159         fprintf(add_fd, "uid: nobody\n");
1160         fprintf(add_fd, "uidNumber: 999\n");
1161         fprintf(add_fd, "homeDirectory: /nobodyshomedir\n");
1162         fprintf(add_fd, "sambaPwdLastSet: 0\n");
1163         fprintf(add_fd, "sambaLogonTime: 0\n");
1164         fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
1165         fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
1166         fprintf(add_fd, "sambaPwdCanChange: 0\n");
1167         fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
1168         fprintf(add_fd, "sambaHomePath: \\\\PDC-SMD3\\homes\\nobody\n");
1169         fprintf(add_fd, "sambaHomeDrive: H:\n");
1170         fprintf(add_fd, "sambaProfilePath: \\\\PDC-SMB3\\profiles\\nobody\n");
1171         fprintf(add_fd, "sambaprimaryGroupSID: %s-514\n", sid);
1172         fprintf(add_fd, "sambaLMPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1173         fprintf(add_fd, "sambaNTPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
1174         fprintf(add_fd, "sambaAcctFlags: [NU\n");
1175         fprintf(add_fd, "sambaSID: %s-2998\n", sid);
1176         fprintf(add_fd, "loginShell: /bin/false\n");
1177         fprintf(add_fd, "\n");
1178         fflush(add_fd);
1179
1180         /* Write the Domain Admins entity */ 
1181         fprintf(add_fd, "# Domain Admins, %s, %s\n", group_attr,
1182                 suffix);
1183         fprintf(add_fd, "dn: cn=Domain Admins,ou=%s,%s\n", group_attr,
1184                 suffix);
1185         fprintf(add_fd, "objectClass: posixGroup\n");
1186         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1187         fprintf(add_fd, "cn: Domain Admins\n");
1188         fprintf(add_fd, "memberUid: Administrator\n");
1189         fprintf(add_fd, "description: Netbios Domain Administrators\n");
1190         fprintf(add_fd, "gidNumber: 512\n");
1191         fprintf(add_fd, "sambaSID: %s-512\n", sid);
1192         fprintf(add_fd, "sambaGroupType: 2\n");
1193         fprintf(add_fd, "displayName: Domain Admins\n");
1194         fprintf(add_fd, "\n");
1195         fflush(add_fd);
1196
1197         /* Write the Domain Users entity */ 
1198         fprintf(add_fd, "# Domain Users, %s, %s\n", group_attr,
1199                 suffix);
1200         fprintf(add_fd, "dn: cn=Domain Users,ou=%s,%s\n", group_attr,
1201                 suffix);
1202         fprintf(add_fd, "objectClass: posixGroup\n");
1203         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1204         fprintf(add_fd, "cn: Domain Users\n");
1205         fprintf(add_fd, "description: Netbios Domain Users\n");
1206         fprintf(add_fd, "gidNumber: 513\n");
1207         fprintf(add_fd, "sambaSID: %s-513\n", sid);
1208         fprintf(add_fd, "sambaGroupType: 2\n");
1209         fprintf(add_fd, "displayName: Domain Users\n");
1210         fprintf(add_fd, "\n");
1211         fflush(add_fd);
1212
1213         /* Write the Domain Guests entity */ 
1214         fprintf(add_fd, "# Domain Guests, %s, %s\n", group_attr,
1215                 suffix);
1216         fprintf(add_fd, "dn: cn=Domain Guests,ou=%s,%s\n", group_attr,
1217                 suffix);
1218         fprintf(add_fd, "objectClass: posixGroup\n");
1219         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1220         fprintf(add_fd, "cn: Domain Guests\n");
1221         fprintf(add_fd, "description: Netbios Domain Guests\n");
1222         fprintf(add_fd, "gidNumber: 514\n");
1223         fprintf(add_fd, "sambaSID: %s-514\n", sid);
1224         fprintf(add_fd, "sambaGroupType: 2\n");
1225         fprintf(add_fd, "displayName: Domain Guests\n");
1226         fprintf(add_fd, "\n");
1227         fflush(add_fd);
1228
1229         /* Write the Domain Computers entity */
1230         fprintf(add_fd, "# Domain Computers, %s, %s\n", group_attr,
1231                 suffix);
1232         fprintf(add_fd, "dn: cn=Domain Computers,ou=%s,%s\n",
1233                 group_attr, suffix);
1234         fprintf(add_fd, "objectClass: posixGroup\n");
1235         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1236         fprintf(add_fd, "gidNumber: 515\n");
1237         fprintf(add_fd, "cn: Domain Computers\n");
1238         fprintf(add_fd, "description: Netbios Domain Computers accounts\n");
1239         fprintf(add_fd, "sambaSID: %s-515\n", sid);
1240         fprintf(add_fd, "sambaGroupType: 2\n");
1241         fprintf(add_fd, "displayName: Domain Computers\n");
1242         fprintf(add_fd, "\n");
1243         fflush(add_fd);
1244
1245         /* Write the Admininistrators Groups entity */
1246         fprintf(add_fd, "# Administrators, %s, %s\n", group_attr,
1247                 suffix);
1248         fprintf(add_fd, "dn: cn=Administrators,ou=%s,%s\n", group_attr,
1249                 suffix);
1250         fprintf(add_fd, "objectClass: posixGroup\n");
1251         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1252         fprintf(add_fd, "gidNumber: 544\n");
1253         fprintf(add_fd, "cn: Administrators\n");
1254         fprintf(add_fd, "description: Netbios Domain Members can fully administer the computer/sambaDomainName\n");
1255         fprintf(add_fd, "sambaSID: %s-544\n", builtin_sid);
1256         fprintf(add_fd, "sambaGroupType: 5\n");
1257         fprintf(add_fd, "displayName: Administrators\n");
1258         fprintf(add_fd, "\n");
1259
1260         /* Write the Print Operator entity */
1261         fprintf(add_fd, "# Print Operators, %s, %s\n", group_attr,
1262                 suffix);
1263         fprintf(add_fd, "dn: cn=Print Operators,ou=%s,%s\n",
1264                 group_attr, suffix);
1265         fprintf(add_fd, "objectClass: posixGroup\n");
1266         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1267         fprintf(add_fd, "gidNumber: 550\n");
1268         fprintf(add_fd, "cn: Print Operators\n");
1269         fprintf(add_fd, "description: Netbios Domain Print Operators\n");
1270         fprintf(add_fd, "sambaSID: %s-550\n", builtin_sid);
1271         fprintf(add_fd, "sambaGroupType: 5\n");
1272         fprintf(add_fd, "displayName: Print Operators\n");
1273         fprintf(add_fd, "\n");
1274         fflush(add_fd);
1275
1276         /* Write the Backup Operators entity */
1277         fprintf(add_fd, "# Backup Operators, %s, %s\n", group_attr,
1278                 suffix);
1279         fprintf(add_fd, "dn: cn=Backup Operators,ou=%s,%s\n",
1280                 group_attr, suffix);
1281         fprintf(add_fd, "objectClass: posixGroup\n");
1282         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1283         fprintf(add_fd, "gidNumber: 551\n");
1284         fprintf(add_fd, "cn: Backup Operators\n");
1285         fprintf(add_fd, "description: Netbios Domain Members can bypass file security to back up files\n");
1286         fprintf(add_fd, "sambaSID: %s-551\n", builtin_sid);
1287         fprintf(add_fd, "sambaGroupType: 5\n");
1288         fprintf(add_fd, "displayName: Backup Operators\n");
1289         fprintf(add_fd, "\n");
1290         fflush(add_fd);
1291
1292         /* Write the Replicators entity */
1293         fprintf(add_fd, "# Replicators, %s, %s\n", group_attr, suffix);
1294         fprintf(add_fd, "dn: cn=Replicators,ou=%s,%s\n", group_attr,
1295                 suffix);
1296         fprintf(add_fd, "objectClass: posixGroup\n");
1297         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1298         fprintf(add_fd, "gidNumber: 552\n");
1299         fprintf(add_fd, "cn: Replicators\n");
1300         fprintf(add_fd, "description: Netbios Domain Supports file replication in a sambaDomainName\n");
1301         fprintf(add_fd, "sambaSID: %s-552\n", builtin_sid);
1302         fprintf(add_fd, "sambaGroupType: 5\n");
1303         fprintf(add_fd, "displayName: Replicators\n");
1304         fprintf(add_fd, "\n");
1305         fflush(add_fd);
1306
1307         /* Deallocate memory, and return */
1308         if (suffix_attr != NULL) SAFE_FREE(suffix_attr);
1309         return NT_STATUS_OK;
1310 }
1311
1312 static NTSTATUS map_populate_groups(GROUPMAP *groupmap, ACCOUNTMAP *accountmap, fstring sid, 
1313                     const char *suffix, const char *builtin_sid)
1314 {
1315         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1316
1317         /* Map the groups created by populate_ldap_for_ldif */
1318         groupmap[0].rid = 512;
1319         groupmap[0].gidNumber = 512;
1320         pstr_sprintf(groupmap[0].sambaSID, "%s-512", sid);
1321         pstr_sprintf(groupmap[0].group_dn, "cn=Domain Admins,ou=%s,%s", 
1322                      group_attr, suffix);
1323         accountmap[0].rid = 512;
1324         pstr_sprintf(accountmap[0].cn, "%s", "Domain Admins");
1325
1326         groupmap[1].rid = 513;
1327         groupmap[1].gidNumber = 513;
1328         pstr_sprintf(groupmap[1].sambaSID, "%s-513", sid);
1329         pstr_sprintf(groupmap[1].group_dn, "cn=Domain Users,ou=%s,%s", 
1330                      group_attr, suffix);
1331         accountmap[1].rid = 513;
1332         pstr_sprintf(accountmap[1].cn, "%s", "Domain Users");
1333
1334         groupmap[2].rid = 514;
1335         groupmap[2].gidNumber = 514;
1336         pstr_sprintf(groupmap[2].sambaSID, "%s-514", sid);
1337         pstr_sprintf(groupmap[2].group_dn, "cn=Domain Guests,ou=%s,%s", 
1338                      group_attr, suffix);
1339         accountmap[2].rid = 514;
1340         pstr_sprintf(accountmap[2].cn, "%s", "Domain Guests");
1341
1342         groupmap[3].rid = 515;
1343         groupmap[3].gidNumber = 515;
1344         pstr_sprintf(groupmap[3].sambaSID, "%s-515", sid);
1345         pstr_sprintf(groupmap[3].group_dn, "cn=Domain Computers,ou=%s,%s",
1346                      group_attr, suffix);
1347         accountmap[3].rid = 515;
1348         pstr_sprintf(accountmap[3].cn, "%s", "Domain Computers");
1349
1350         groupmap[4].rid = 544;
1351         groupmap[4].gidNumber = 544;
1352         pstr_sprintf(groupmap[4].sambaSID, "%s-544", builtin_sid);
1353         pstr_sprintf(groupmap[4].group_dn, "cn=Administrators,ou=%s,%s",
1354                      group_attr, suffix);
1355         accountmap[4].rid = 515;
1356         pstr_sprintf(accountmap[4].cn, "%s", "Administrators");
1357
1358         groupmap[5].rid = 550;
1359         groupmap[5].gidNumber = 550;
1360         pstr_sprintf(groupmap[5].sambaSID, "%s-550", builtin_sid);
1361         pstr_sprintf(groupmap[5].group_dn, "cn=Print Operators,ou=%s,%s",
1362                      group_attr, suffix);
1363         accountmap[5].rid = 550;
1364         pstr_sprintf(accountmap[5].cn, "%s", "Print Operators");
1365
1366         groupmap[6].rid = 551;
1367         groupmap[6].gidNumber = 551;
1368         pstr_sprintf(groupmap[6].sambaSID, "%s-551", builtin_sid);
1369         pstr_sprintf(groupmap[6].group_dn, "cn=Backup Operators,ou=%s,%s",
1370                      group_attr, suffix);
1371         accountmap[6].rid = 551;
1372         pstr_sprintf(accountmap[6].cn, "%s", "Backup Operators");
1373
1374         groupmap[7].rid = 552;
1375         groupmap[7].gidNumber = 552;
1376         pstr_sprintf(groupmap[7].sambaSID, "%s-552", builtin_sid);
1377         pstr_sprintf(groupmap[7].group_dn, "cn=Replicators,ou=%s,%s",
1378                      group_attr, suffix);
1379         accountmap[7].rid = 551;
1380         pstr_sprintf(accountmap[7].cn, "%s", "Replicators");
1381         return NT_STATUS_OK;
1382 }
1383
1384 static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1385                          FILE *add_fd, fstring sid, char *suffix)
1386 {
1387         fstring groupname;
1388         uint32 grouptype = 0, g_rid = 0;
1389         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1390
1391         /* Get the group name */
1392         unistr2_to_ascii(groupname, 
1393                          &(delta->group_info.uni_grp_name),
1394                          sizeof(groupname)-1);
1395
1396         /* Set up the group type (always 2 for group info) */
1397         grouptype = 2;
1398
1399         /* These groups are entered by populate_ldap_for_ldif */
1400         if (strcmp(groupname, "Domain Admins") == 0 ||
1401             strcmp(groupname, "Domain Users") == 0 ||
1402             strcmp(groupname, "Domain Guests") == 0 ||
1403             strcmp(groupname, "Domain Computers") == 0 ||
1404             strcmp(groupname, "Administrators") == 0 ||
1405             strcmp(groupname, "Print Operators") == 0 ||
1406             strcmp(groupname, "Backup Operators") == 0 ||
1407             strcmp(groupname, "Replicators") == 0) {
1408                 return NT_STATUS_OK;
1409         } else {
1410                 /* Increment the gid for the new group */
1411                 ldif_gid++;
1412         }
1413
1414         /* Map the group rid, gid, and dn */
1415         g_rid = delta->group_info.gid.g_rid;
1416         groupmap->rid = g_rid;
1417         groupmap->gidNumber = ldif_gid;
1418         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1419         pstr_sprintf(groupmap->group_dn, 
1420                      "cn=%s,ou=%s,%s", groupname, group_attr, suffix);
1421
1422         /* Write the data to the temporary add ldif file */
1423         fprintf(add_fd, "# %s, %s, %s\n", groupname, group_attr,
1424                 suffix);
1425         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", groupname, group_attr,
1426                 suffix);
1427         fprintf(add_fd, "objectClass: posixGroup\n");
1428         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1429         fprintf(add_fd, "cn: %s\n", groupname);
1430         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1431         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1432         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1433         fprintf(add_fd, "displayName: %s\n", groupname);
1434         fprintf(add_fd, "\n");
1435         fflush(add_fd);
1436
1437         /* Return */
1438         return NT_STATUS_OK;
1439 }
1440
1441 static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1442                            ACCOUNTMAP *accountmap, FILE *add_fd,
1443                            fstring sid, char *suffix, int alloced)
1444 {
1445         fstring username, logonscript, homedrive, homepath = "", homedir = "";
1446         fstring hex_nt_passwd, hex_lm_passwd;
1447         fstring description, fullname, sambaSID;
1448         uchar lm_passwd[16], nt_passwd[16];
1449         char *flags;
1450         const char* nopasswd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1451         static uchar zero_buf[16];
1452         uint32 rid = 0, group_rid = 0, gidNumber = 0;
1453         time_t unix_time;
1454         int i;
1455
1456         /* Get the username */
1457         unistr2_to_ascii(username, 
1458                          &(delta->account_info.uni_acct_name),
1459                          sizeof(username)-1);
1460
1461         /* Get the rid */
1462         rid = delta->account_info.user_rid;
1463
1464         /* Map the rid and username for group member info later */
1465         accountmap->rid = rid;
1466         pstr_sprintf(accountmap->cn, "%s", username);
1467
1468         /* Get the home directory */
1469         if (delta->account_info.acb_info & ACB_NORMAL) {
1470                 unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
1471                                  sizeof(homedir)-1);
1472                 if (!*homedir) {
1473                         pstr_sprintf(homedir, "/home/%s", username);
1474                 } else {
1475                         pstr_sprintf(homedir, "/nobodyshomedir");
1476                 }
1477         }       
1478
1479         /* Get the logon script */
1480         unistr2_to_ascii(logonscript, &(delta->account_info.uni_logon_script),
1481                         sizeof(logonscript)-1);
1482
1483         /* Get the home drive */
1484         unistr2_to_ascii(homedrive, &(delta->account_info.uni_dir_drive),
1485                         sizeof(homedrive)-1);
1486
1487         /* Get the description */
1488         unistr2_to_ascii(description, &(delta->account_info.uni_acct_desc),
1489                          sizeof(description)-1);
1490         if (!*description) {
1491                 pstr_sprintf(description, "System User");
1492         }
1493
1494         /* Get the display name */
1495         unistr2_to_ascii(fullname, &(delta->account_info.uni_full_name),
1496                          sizeof(fullname)-1);
1497
1498         /* Get lm and nt password data */
1499         if (memcmp(delta->account_info.pass.buf_lm_pwd, zero_buf, 16) != 0) {
1500                 sam_pwd_hash(delta->account_info.user_rid, 
1501                              delta->account_info.pass.buf_lm_pwd, 
1502                              lm_passwd, 0);
1503                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, 
1504                               delta->account_info.acb_info);
1505         } else {
1506                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
1507         }
1508         if (memcmp(delta->account_info.pass.buf_nt_pwd, zero_buf, 16) != 0) {
1509                 sam_pwd_hash(delta->account_info.user_rid, 
1510                              delta->account_info.pass.buf_nt_pwd, 
1511                                      nt_passwd, 0);
1512                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, 
1513                               delta->account_info.acb_info);
1514         } else {
1515                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
1516         }
1517         unix_time = nt_time_to_unix(&(delta->account_info.pwd_last_set_time));
1518
1519         /* The nobody user is entered by populate_ldap_for_ldif */
1520         if (strcmp(username, "nobody") == 0) {
1521                 return NT_STATUS_OK;
1522         } else {
1523                 /* Increment the uid for the new user */
1524                 ldif_uid++;
1525         }
1526
1527         /* Set up group id and sambaSID for the user */
1528         group_rid = delta->account_info.group_rid;
1529         for (i=0; i<alloced; i++) {
1530                 if (groupmap[i].rid == group_rid) break;
1531         }
1532         if (i == alloced){
1533                 DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1534                           group_rid));
1535                 return NT_STATUS_UNSUCCESSFUL;
1536         }
1537         gidNumber = groupmap[i].gidNumber;
1538         pstr_sprintf(sambaSID, groupmap[i].sambaSID);
1539
1540         /* Set up sambaAcctFlags */
1541         flags = pdb_encode_acct_ctrl(delta->account_info.acb_info,
1542                                      NEW_PW_FORMAT_SPACE_PADDED_LEN);
1543
1544         /* Add the user to the temporary add ldif file */
1545         fprintf(add_fd, "# %s, %s, %s\n", username, 
1546                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1547         fprintf(add_fd, "dn: uid=%s,ou=%s,%s\n", username, 
1548                 sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
1549         fprintf(add_fd, "ObjectClass: top\n");
1550         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1551         fprintf(add_fd, "objectClass: posixAccount\n");
1552         fprintf(add_fd, "objectClass: shadowAccount\n");
1553         fprintf(add_fd, "objectClass: sambaSamAccount\n");
1554         fprintf(add_fd, "cn: %s\n", username);
1555         fprintf(add_fd, "sn: %s\n", username);
1556         fprintf(add_fd, "uid: %s\n", username);
1557         fprintf(add_fd, "uidNumber: %d\n", ldif_uid);
1558         fprintf(add_fd, "gidNumber: %d\n", gidNumber);
1559         fprintf(add_fd, "homeDirectory: %s\n", homedir);
1560         if (*homepath)
1561                 fprintf(add_fd, "SambaHomePath: %s\n", homepath);
1562         if (*homedrive)
1563                 fprintf(add_fd, "SambaHomeDrive: %s\n", homedrive);
1564         if (*logonscript)
1565                 fprintf(add_fd, "SambaLogonScript: %s\n", logonscript);
1566         fprintf(add_fd, "loginShell: %s\n", 
1567                 ((delta->account_info.acb_info & ACB_NORMAL) ?
1568                  "/bin/bash" : "/bin/false"));
1569         fprintf(add_fd, "gecos: System User\n");
1570         fprintf(add_fd, "description: %s\n", description);
1571         fprintf(add_fd, "sambaSID: %s-%d\n", sid, rid);
1572         fprintf(add_fd, "sambaPrimaryGroupSID: %s\n", sambaSID);
1573         if(*fullname)
1574                 fprintf(add_fd, "displayName: %s\n", fullname);
1575         if (strcmp(nopasswd, hex_lm_passwd) != 0)
1576                 fprintf(add_fd, "sambaLMPassword: %s\n", hex_lm_passwd);
1577         if (strcmp(nopasswd, hex_nt_passwd) != 0)
1578                 fprintf(add_fd, "sambaNTPassword: %s\n", hex_nt_passwd);
1579         fprintf(add_fd, "sambaPwdLastSet: %d\n", (int)unix_time);
1580         fprintf(add_fd, "sambaAcctFlags: %s\n", flags);
1581         fprintf(add_fd, "\n");
1582         fflush(add_fd);
1583
1584         /* Return */
1585         return NT_STATUS_OK;
1586 }
1587
1588 static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1589                          FILE *add_fd, fstring sid, char *suffix, 
1590                          unsigned db_type)
1591 {
1592         fstring aliasname, description;
1593         uint32 grouptype = 0, g_rid = 0;
1594         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1595
1596         /* Get the alias name */
1597         unistr2_to_ascii(aliasname, &(delta->alias_info.uni_als_name),
1598                          sizeof(aliasname)-1);
1599
1600         /* Get the alias description */
1601         unistr2_to_ascii(description, &(delta->alias_info.uni_als_desc),
1602                          sizeof(description)-1);
1603
1604         /* Set up the group type */
1605         switch (db_type) {
1606                 case SAM_DATABASE_DOMAIN:
1607                         grouptype = 4;
1608                         break;
1609                 case SAM_DATABASE_BUILTIN:
1610                         grouptype = 5;
1611                         break;
1612                 default:
1613                         grouptype = 4;
1614                         break;
1615         }
1616
1617         /*
1618         These groups are entered by populate_ldap_for_ldif
1619         Note that populate creates a group called Relicators, 
1620         but NT returns a group called Replicator
1621         */
1622         if (strcmp(aliasname, "Domain Admins") == 0 ||
1623             strcmp(aliasname, "Domain Users") == 0 ||
1624             strcmp(aliasname, "Domain Guests") == 0 ||
1625             strcmp(aliasname, "Domain Computers") == 0 ||
1626             strcmp(aliasname, "Administrators") == 0 ||
1627             strcmp(aliasname, "Print Operators") == 0 ||
1628             strcmp(aliasname, "Backup Operators") == 0 ||
1629             strcmp(aliasname, "Replicator") == 0) {
1630                 return NT_STATUS_OK;
1631         } else {
1632                 /* Increment the gid for the new group */
1633                 ldif_gid++;
1634         }
1635
1636         /* Map the group rid and gid */
1637         g_rid = delta->group_info.gid.g_rid;
1638         groupmap->gidNumber = ldif_gid;
1639         pstr_sprintf(groupmap->sambaSID, "%s-%d", sid, g_rid);
1640
1641         /* Write the data to the temporary add ldif file */
1642         fprintf(add_fd, "# %s, %s, %s\n", aliasname, group_attr,
1643                 suffix);
1644         fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", aliasname, group_attr,
1645                 suffix);
1646         fprintf(add_fd, "objectClass: posixGroup\n");
1647         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1648         fprintf(add_fd, "cn: %s\n", aliasname);
1649         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1650         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1651         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1652         fprintf(add_fd, "displayName: %s\n", aliasname);
1653         fprintf(add_fd, "description: %s\n", description);
1654         fprintf(add_fd, "\n");
1655         fflush(add_fd);
1656
1657         /* Return */
1658         return NT_STATUS_OK;
1659 }
1660
1661 static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR *hdr_delta,
1662                             GROUPMAP *groupmap, ACCOUNTMAP *accountmap, 
1663                             FILE *mod_fd, int alloced)
1664 {
1665         fstring group_dn;
1666         uint32 group_rid = 0, rid = 0;
1667         int i, j, k;
1668
1669         /* Get the dn for the group */
1670         if (delta->grp_mem_info.num_members > 0) {
1671                 group_rid = hdr_delta->target_rid;
1672                 for (j=0; j<alloced; j++) {
1673                         if (groupmap[j].rid == group_rid) break;
1674                 }
1675                 if (j == alloced){
1676                         DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1677                                   group_rid));
1678                         return NT_STATUS_UNSUCCESSFUL;
1679                 }
1680                 pstr_sprintf(group_dn, "%s", groupmap[j].group_dn);
1681                 fprintf(mod_fd, "dn: %s\n", group_dn);
1682
1683                 /* Get the cn for each member */
1684                 for (i=0; i<delta->grp_mem_info.num_members; i++) {
1685                         rid = delta->grp_mem_info.rids[i];
1686                         for (k=0; k<alloced; k++) {
1687                                 if (accountmap[k].rid == rid) break;
1688                         }
1689                         if (k == alloced){
1690                                 DEBUG(1, ("Could not find rid %d in accountmap array\n", rid));
1691                                 return NT_STATUS_UNSUCCESSFUL;
1692                         }
1693                         fprintf(mod_fd, "memberUid: %s\n", accountmap[k].cn);
1694                 }
1695                 fprintf(mod_fd, "\n");
1696         }
1697         fflush(mod_fd);
1698
1699         /* Return */
1700         return NT_STATUS_OK;
1701 }
1702
1703 static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
1704                                         uint32 db_type,
1705                                         DOM_SID dom_sid,
1706                                         const char *user_file)
1707 {
1708         char *suffix;
1709         const char *builtin_sid = "S-1-5-32";
1710         char *ldif_file;
1711         fstring sid, domainname;
1712         uint32 sync_context = 0;
1713         NTSTATUS result;
1714         int k;
1715         TALLOC_CTX *mem_ctx;
1716         SAM_DELTA_HDR *hdr_deltas;
1717         SAM_DELTA_CTR *deltas;
1718         uint32 num_deltas;
1719         const char *add_ldif = "/tmp/add.ldif", *mod_ldif = "/tmp/mod.ldif";
1720         FILE *add_fd, *mod_fd, *ldif_fd;
1721         char sys_cmd[1024];
1722         int num_alloced = 0, g_index = 0, a_index = 0, sys_cmd_result;
1723
1724         /* Set up array for mapping accounts to groups */
1725         /* Array element is the group rid */
1726         GROUPMAP *groupmap = NULL;
1727
1728         /* Set up array for mapping account rid's to cn's */
1729         /* Array element is the account rid */
1730         ACCOUNTMAP *accountmap = NULL; 
1731
1732         if (!(mem_ctx = talloc_init("fetch_database"))) {
1733                 return NT_STATUS_NO_MEMORY;
1734         }
1735
1736         /* Ensure we have an output file */
1737         if (user_file)
1738                 ldif_file = talloc_strdup(mem_ctx, user_file);
1739         else
1740                 ldif_file = talloc_strdup(mem_ctx, "/tmp/tmp.ldif");
1741         
1742         if (ldif_file == NULL)
1743                 return NT_STATUS_NO_MEMORY;
1744
1745         /* Open the add and mod ldif files */
1746         add_fd = fopen(add_ldif, "a");
1747         mod_fd = fopen(mod_ldif, "a");
1748         if (add_fd == NULL || mod_fd == NULL) {
1749                 DEBUG(1, ("Could not open %s\n", add_ldif));
1750                 return NT_STATUS_UNSUCCESSFUL;
1751         } 
1752
1753         /* Open the user's ldif file */
1754         ldif_fd = fopen(ldif_file, "a");
1755         if (ldif_fd == NULL) {
1756                 DEBUG(1, ("Could not open %s\n", ldif_file));
1757                 return NT_STATUS_UNSUCCESSFUL;
1758         }
1759
1760         /* Get the sid */
1761         sid_to_string(sid, &dom_sid);
1762
1763         /* Get the ldap suffix */
1764         suffix = lp_ldap_suffix();
1765         if (suffix == NULL || strcmp(suffix, "") == 0) {
1766                 DEBUG(0,("ldap suffix missing from smb.conf--exiting\n"));
1767                 exit(1);
1768         }
1769
1770         /* Get other smb.conf data */
1771         if (!(lp_workgroup()) || !*(lp_workgroup())) {
1772                 DEBUG(0,("workgroup missing from smb.conf--exiting\n"));
1773                 exit(1);
1774         }
1775
1776         /* Allocate initial memory for groupmap and accountmap arrays */
1777         if (init_ldap == 1) {
1778                 groupmap = SMB_MALLOC_ARRAY(GROUPMAP, 8);
1779                 accountmap = SMB_MALLOC_ARRAY(ACCOUNTMAP, 8);
1780                 if (groupmap == NULL || accountmap == NULL) {
1781                         DEBUG(1,("GROUPMAP malloc failed\n"));
1782                         return NT_STATUS_NO_MEMORY;
1783                 }
1784
1785                 /* Initialize the arrays */
1786                 memset(groupmap, 0, sizeof(GROUPMAP)*8);
1787                 memset(accountmap, 0, sizeof(ACCOUNTMAP)*8);
1788
1789                 /* Remember how many we malloced */
1790                 num_alloced = 8;
1791
1792                 /* Initial database population */
1793                 populate_ldap_for_ldif(sid, suffix, builtin_sid, add_fd);
1794                 map_populate_groups(groupmap, accountmap, sid, suffix,
1795                             builtin_sid);
1796
1797                 /* Don't do this again */
1798                 init_ldap = 0;
1799         }
1800
1801         /* Announce what we are doing */
1802         switch( db_type ) {
1803                 case SAM_DATABASE_DOMAIN:
1804                         d_printf("Fetching DOMAIN database\n");
1805                         break;
1806                 case SAM_DATABASE_BUILTIN:
1807                         d_printf("Fetching BUILTIN database\n");
1808                         break;
1809                 case SAM_DATABASE_PRIVS:
1810                         d_printf("Fetching PRIVS databases\n");
1811                         break;
1812                 default:
1813                         d_printf("Fetching unknown database type %u\n", db_type );
1814                         break;
1815         }
1816
1817         do {
1818                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
1819                                                db_type, sync_context,
1820                                                &num_deltas, &hdr_deltas, 
1821                                                &deltas);
1822                 if (!NT_STATUS_IS_OK(result) &&
1823                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1824                         return NT_STATUS_OK;
1825                 }
1826
1827                 /* Re-allocate memory for groupmap and accountmap arrays */
1828                 groupmap = SMB_REALLOC_ARRAY(groupmap, GROUPMAP,
1829                                         num_deltas+num_alloced);
1830                 accountmap = SMB_REALLOC_ARRAY(accountmap, ACCOUNTMAP,
1831                                         num_deltas+num_alloced);
1832                 if (groupmap == NULL || accountmap == NULL) {
1833                         DEBUG(1,("GROUPMAP malloc failed\n"));
1834                         SAFE_FREE(groupmap);
1835                         SAFE_FREE(accountmap);
1836                         return NT_STATUS_NO_MEMORY;
1837                 }
1838
1839                 /* Initialize the new records */
1840                 memset(&groupmap[num_alloced], 0, 
1841                        sizeof(GROUPMAP)*num_deltas);
1842                 memset(&accountmap[num_alloced], 0,
1843                        sizeof(ACCOUNTMAP)*num_deltas);
1844
1845                 /* Remember how many we alloced this time */
1846                 num_alloced += num_deltas;
1847
1848                 /* Loop through the deltas */
1849                 for (k=0; k<num_deltas; k++) {
1850                         switch(hdr_deltas[k].type) {
1851                                 case SAM_DELTA_DOMAIN_INFO:
1852                                         /* Is this case needed? */
1853                                         unistr2_to_ascii(domainname, 
1854                                         &deltas[k].domain_info.uni_dom_name,
1855                                                 sizeof(domainname)-1);
1856                                         break;
1857
1858                                 case SAM_DELTA_GROUP_INFO:
1859                                         fetch_group_info_to_ldif(
1860                                                 &deltas[k], &groupmap[g_index],
1861                                                 add_fd, sid, suffix);
1862                                         g_index++;
1863                                         break;
1864
1865                                 case SAM_DELTA_ACCOUNT_INFO:
1866                                         fetch_account_info_to_ldif(
1867                                                 &deltas[k], groupmap, 
1868                                                 &accountmap[a_index], add_fd,
1869                                                 sid, suffix, num_alloced);
1870                                         a_index++;
1871                                         break;
1872
1873                                 case SAM_DELTA_ALIAS_INFO:
1874                                         fetch_alias_info_to_ldif(
1875                                                 &deltas[k], &groupmap[g_index],
1876                                                 add_fd, sid, suffix, db_type);
1877                                         g_index++;
1878                                         break;
1879
1880                                 case SAM_DELTA_GROUP_MEM:
1881                                         fetch_groupmem_info_to_ldif(
1882                                                 &deltas[k], &hdr_deltas[k], 
1883                                                 groupmap, accountmap, 
1884                                                 mod_fd, num_alloced);
1885                                         break;
1886
1887                                 case SAM_DELTA_ALIAS_MEM:
1888                                         break;
1889                                 case SAM_DELTA_POLICY_INFO:
1890                                         break;
1891                                 case SAM_DELTA_PRIVS_INFO:
1892                                         break;
1893                                 case SAM_DELTA_TRUST_DOMS:
1894                                         /* Implemented but broken */
1895                                         break;
1896                                 case SAM_DELTA_SECRET_INFO:
1897                                         /* Implemented but broken */
1898                                         break;
1899                                 case SAM_DELTA_RENAME_GROUP:
1900                                         /* Not yet implemented */
1901                                         break;
1902                                 case SAM_DELTA_RENAME_USER:
1903                                         /* Not yet implemented */
1904                                         break;
1905                                 case SAM_DELTA_RENAME_ALIAS:
1906                                         /* Not yet implemented */
1907                                         break;
1908                                 case SAM_DELTA_DELETE_GROUP:
1909                                         /* Not yet implemented */
1910                                         break;
1911                                 case SAM_DELTA_DELETE_USER:
1912                                         /* Not yet implemented */
1913                                         break;
1914                                 case SAM_DELTA_MODIFIED_COUNT:
1915                                         break;
1916                                 default:
1917                                 break;
1918                         } /* end of switch */
1919                 } /* end of for loop */
1920
1921                 /* Increment sync_context */
1922                 sync_context += 1;
1923
1924         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1925
1926         /* Close the ldif files */
1927         fclose(add_fd);
1928         fclose(mod_fd);
1929
1930         /* Write ldif data to the user's file */
1931         if (db_type == SAM_DATABASE_DOMAIN) {
1932                 fprintf(ldif_fd,
1933                         "# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
1934                 fprintf(ldif_fd,
1935                         "# =================================\n\n");
1936                 fflush(ldif_fd);
1937         } else if (db_type == SAM_DATABASE_BUILTIN) {
1938                 fprintf(ldif_fd,
1939                         "# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
1940                 fprintf(ldif_fd,
1941                         "# ==================================\n\n");
1942                 fflush(ldif_fd);
1943         }
1944         pstr_sprintf(sys_cmd, "cat %s >> %s", add_ldif, ldif_file);
1945         sys_cmd_result = system(sys_cmd);
1946         if (sys_cmd_result) {
1947                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1948                         sys_cmd, strerror(errno));
1949                 return NT_STATUS_UNSUCCESSFUL;
1950         }
1951         if (db_type == SAM_DATABASE_DOMAIN) {
1952                 fprintf(ldif_fd,
1953                         "# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
1954                 fprintf(ldif_fd,
1955                         "# ====================================\n\n");
1956                 fflush(ldif_fd);
1957         } else if (db_type == SAM_DATABASE_BUILTIN) {
1958                 fprintf(ldif_fd,
1959                         "# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
1960                 fprintf(ldif_fd,
1961                         "# =====================================\n\n");
1962                 fflush(ldif_fd);
1963         }
1964         pstr_sprintf(sys_cmd, "cat %s >> %s", mod_ldif, ldif_file);
1965         sys_cmd_result = system(sys_cmd);
1966         if (sys_cmd_result) {
1967                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1968                         sys_cmd, strerror(errno));
1969                 return NT_STATUS_UNSUCCESSFUL;
1970         }
1971
1972         /* Delete the temporary ldif files */
1973         pstr_sprintf(sys_cmd, "rm -f %s %s", add_ldif, mod_ldif);
1974         sys_cmd_result = system(sys_cmd);
1975         if (sys_cmd_result) {
1976                 d_fprintf(stderr, "%s failed.  Error was (%s)\n",
1977                         sys_cmd, strerror(errno));
1978                 return NT_STATUS_UNSUCCESSFUL;
1979         }
1980
1981         /* Close the ldif file */
1982         fclose(ldif_fd);
1983
1984         /* Deallocate memory for the mapping arrays */
1985         SAFE_FREE(groupmap);
1986         SAFE_FREE(accountmap);
1987
1988         /* Return */
1989         talloc_destroy(mem_ctx);
1990         return NT_STATUS_OK;
1991 }
1992
1993 /** 
1994  * Basic usage function for 'net rpc vampire'
1995  * @param argc  Standard main() style argc
1996  * @param argc  Standard main() style argv.  Initial components are already
1997  *              stripped
1998  **/
1999
2000 int rpc_vampire_usage(int argc, const char **argv) 
2001 {       
2002         d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"\
2003                  "\t to pull accounts from a remote PDC where we are a BDC\n"\
2004                  "\t\t no args puts accounts in local passdb from smb.conf\n"\
2005                  "\t\t ldif - put accounts in ldif format (file defaults to /tmp/tmp.ldif\n");
2006
2007         net_common_flags_usage(argc, argv);
2008         return -1;
2009 }
2010
2011
2012 /* dump sam database via samsync rpc calls */
2013 NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
2014                                 const char *domain_name, 
2015                                 struct cli_state *cli,
2016                                 struct rpc_pipe_client *pipe_hnd,
2017                                 TALLOC_CTX *mem_ctx, 
2018                                 int argc,
2019                                 const char **argv) 
2020 {
2021         NTSTATUS result;
2022         fstring my_dom_sid_str;
2023         fstring rem_dom_sid_str;
2024
2025         if (!sid_equal(domain_sid, get_global_sam_sid())) {
2026                 d_printf("Cannot import users from %s at this time, "
2027                          "as the current domain:\n\t%s: %s\nconflicts "
2028                          "with the remote domain\n\t%s: %s\n"
2029                          "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
2030                          domain_name,
2031                          get_global_sam_name(), sid_to_string(my_dom_sid_str, 
2032                                                               get_global_sam_sid()),
2033                          domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
2034                          domain_name);
2035                 return NT_STATUS_UNSUCCESSFUL;
2036         }
2037
2038         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2039                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_DOMAIN,
2040                                         *domain_sid, argv[1]);
2041         } else {
2042                 result = fetch_database(pipe_hnd, SAM_DATABASE_DOMAIN, *domain_sid);
2043         }
2044
2045         if (!NT_STATUS_IS_OK(result)) {
2046                 d_fprintf(stderr, "Failed to fetch domain database: %s\n",
2047                          nt_errstr(result));
2048                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
2049                         d_fprintf(stderr, "Perhaps %s is a Windows 2000 native "
2050                                  "mode domain?\n", domain_name);
2051                 goto fail;
2052         }
2053
2054         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2055                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_BUILTIN, 
2056                                         global_sid_Builtin, argv[1]);
2057         } else {
2058                 result = fetch_database(pipe_hnd, SAM_DATABASE_BUILTIN, global_sid_Builtin);
2059         }
2060
2061         if (!NT_STATUS_IS_OK(result)) {
2062                 d_fprintf(stderr, "Failed to fetch builtin database: %s\n",
2063                          nt_errstr(result));
2064                 goto fail;
2065         }
2066
2067         /* Currently we crash on PRIVS somewhere in unmarshalling */
2068         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
2069
2070 fail:
2071         return result;
2072 }