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