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