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