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