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