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