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