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