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