r25026: Move param/param.h out of includes.h
[kai/samba-autobuild/.git] / source4 / libnet / libnet_samsync_ldb.c
1 /* 
2    Unix SMB/CIFS implementation.
3    
4    Extract the user/system database from a remote SamSync server
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
7    Copyright (C) Andrew Tridgell 2004
8    Copyright (C) Volker Lendecke 2004
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24
25 #include "includes.h"
26 #include "libnet/libnet.h"
27 #include "libcli/ldap/ldap.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "auth/auth.h"
30 #include "librpc/gen_ndr/ndr_misc.h"
31 #include "db_wrap.h"
32 #include "libcli/security/security.h"
33 #include "librpc/rpc/dcerpc.h"
34 #include "param/param.h"
35
36 struct samsync_ldb_secret {
37         struct samsync_ldb_secret *prev, *next;
38         DATA_BLOB secret;
39         char *name;
40         NTTIME mtime;
41 };
42
43 struct samsync_ldb_trusted_domain {
44         struct samsync_ldb_trusted_domain *prev, *next;
45         struct dom_sid *sid;
46         char *name;
47 };
48
49 struct samsync_ldb_state {
50         /* Values from the LSA lookup */
51         const struct libnet_SamSync_state *samsync_state;
52
53         struct dom_sid *dom_sid[3];
54         struct ldb_context *sam_ldb, *remote_ldb;
55         struct ldb_dn *base_dn[3];
56         struct samsync_ldb_secret *secrets;
57         struct samsync_ldb_trusted_domain *trusted_domains;
58 };
59
60 static NTSTATUS samsync_ldb_add_foreignSecurityPrincipal(TALLOC_CTX *mem_ctx,
61                                                          struct samsync_ldb_state *state,
62                                                          struct dom_sid *sid,
63                                                          struct ldb_dn **fsp_dn,
64                                                          char **error_string)
65 {
66         const char *sidstr = dom_sid_string(mem_ctx, sid);
67         /* We assume that ForeignSecurityPrincipals are under the BASEDN of the main domain */
68         struct ldb_dn *basedn = samdb_search_dn(state->sam_ldb, mem_ctx,
69                                                 state->base_dn[SAM_DATABASE_DOMAIN],
70                                                 "(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
71         struct ldb_message *msg;
72         int ret;
73
74         if (!sidstr) {
75                 return NT_STATUS_NO_MEMORY;
76         }
77
78         if (basedn == NULL) {
79                 *error_string = talloc_asprintf(mem_ctx, 
80                                                 "Failed to find DN for "
81                                                 "ForeignSecurityPrincipal container under %s",
82                                                 ldb_dn_get_linearized(state->base_dn[SAM_DATABASE_DOMAIN]));
83                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
84         }
85         
86         msg = ldb_msg_new(mem_ctx);
87         if (msg == NULL) {
88                 return NT_STATUS_NO_MEMORY;
89         }
90
91         /* add core elements to the ldb_message for the alias */
92         msg->dn = basedn;
93         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
94                 return NT_STATUS_UNSUCCESSFUL;
95         
96         samdb_msg_add_string(state->sam_ldb, mem_ctx, msg,
97                              "objectClass",
98                              "foreignSecurityPrincipal");
99
100         *fsp_dn = msg->dn;
101
102         /* create the alias */
103         ret = samdb_add(state->sam_ldb, mem_ctx, msg);
104         if (ret != 0) {
105                 *error_string = talloc_asprintf(mem_ctx, "Failed to create foreignSecurityPrincipal "
106                                                 "record %s: %s",
107                                                 ldb_dn_get_linearized(msg->dn),
108                                                 ldb_errstring(state->sam_ldb));
109                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
110         }
111         return NT_STATUS_OK;
112 }
113
114 static NTSTATUS samsync_ldb_handle_domain(TALLOC_CTX *mem_ctx,
115                                           struct samsync_ldb_state *state,
116                                           enum netr_SamDatabaseID database,
117                                           struct netr_DELTA_ENUM *delta,
118                                           char **error_string) 
119 {
120         struct netr_DELTA_DOMAIN *domain = delta->delta_union.domain;
121         const char *domain_name = domain->domain_name.string;
122         struct ldb_message *msg;
123         int ret;
124         
125         msg = ldb_msg_new(mem_ctx);
126         if (msg == NULL) {
127                 return NT_STATUS_NO_MEMORY;
128         }
129
130         if (database == SAM_DATABASE_DOMAIN) {
131                 struct ldb_dn *partitions_basedn;
132                 const char *domain_attrs[] =  {"nETBIOSName", "nCName", NULL};
133                 struct ldb_message **msgs_domain;
134                 int ret_domain;
135
136                 partitions_basedn = samdb_partitions_dn(state->sam_ldb, mem_ctx);
137
138                 ret_domain = gendb_search(state->sam_ldb, mem_ctx, partitions_basedn, &msgs_domain, domain_attrs,
139                                           "(&(&(nETBIOSName=%s)(objectclass=crossRef))(ncName=*))", 
140                                           domain_name);
141                 if (ret_domain == -1) {
142                         *error_string = talloc_asprintf(mem_ctx, "gendb_search for domain failed: %s", ldb_errstring(state->sam_ldb));
143                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
144                 }
145                 
146                 if (ret_domain != 1) {
147                         *error_string = talloc_asprintf(mem_ctx, "Failed to find existing domain record for %s: %d results", domain_name,
148                                                         ret_domain);
149                         return NT_STATUS_NO_SUCH_DOMAIN;                
150                 }
151
152                 state->base_dn[database] = samdb_result_dn(state->sam_ldb, state, msgs_domain[0], "nCName", NULL);
153
154                 if (state->dom_sid[database]) {
155                         /* Update the domain sid with the incoming
156                          * domain (found on LSA pipe, database sid may
157                          * be random) */
158                         samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, 
159                                               msg, "objectSid", state->dom_sid[database]);
160                 } else {
161                         /* Well, we will have to use the one from the database */
162                         state->dom_sid[database] = samdb_search_dom_sid(state->sam_ldb, state,
163                                                                         state->base_dn[database], 
164                                                                         "objectSid", NULL);
165                 }
166
167                 if (state->samsync_state->domain_guid) {
168                         NTSTATUS nt_status;
169                         struct ldb_val v;
170                         nt_status = ndr_push_struct_blob(&v, msg, state->samsync_state->domain_guid,
171                                                          (ndr_push_flags_fn_t)ndr_push_GUID);
172                         if (!NT_STATUS_IS_OK(nt_status)) {
173                                 *error_string = talloc_asprintf(mem_ctx, "ndr_push of domain GUID failed!");
174                                 return nt_status;
175                         }
176                         
177                         ldb_msg_add_value(msg, "objectGUID", &v, NULL);
178                 }
179         } else if (database == SAM_DATABASE_BUILTIN) {
180                 /* work out the builtin_dn - useful for so many calls its worth
181                    fetching here */
182                 const char *dnstring = samdb_search_string(state->sam_ldb, mem_ctx, NULL,
183                                                            "distinguishedName", "objectClass=builtinDomain");
184                 state->base_dn[database] = ldb_dn_new(state, state->sam_ldb, dnstring);
185                 if ( ! ldb_dn_validate(state->base_dn[database])) {
186                         return NT_STATUS_INTERNAL_ERROR;
187                 }
188         } else {
189                 /* PRIVs DB */
190                 return NT_STATUS_INVALID_PARAMETER;
191         }
192
193         msg->dn = talloc_reference(mem_ctx, state->base_dn[database]);
194         if (!msg->dn) {
195                 return NT_STATUS_NO_MEMORY;
196         }
197
198         samdb_msg_add_string(state->sam_ldb, mem_ctx, 
199                              msg, "oEMInformation", domain->comment.string);
200
201         samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
202                             msg, "forceLogoff", domain->force_logoff_time);
203
204         samdb_msg_add_uint(state->sam_ldb, mem_ctx, 
205                            msg, "minPwdLen", domain->min_password_length);
206
207         samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
208                             msg, "maxPwdAge", domain->max_password_age);
209
210         samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
211                             msg, "minPwdAge", domain->min_password_age);
212
213         samdb_msg_add_uint(state->sam_ldb, mem_ctx, 
214                            msg, "pwdHistoryLength", domain->password_history_length);
215
216         samdb_msg_add_uint64(state->sam_ldb, mem_ctx, 
217                              msg, "modifiedCount", 
218                              domain->sequence_num);
219
220         samdb_msg_add_uint64(state->sam_ldb, mem_ctx, 
221                              msg, "creationTime", domain->domain_create_time);
222
223         /* TODO: Account lockout, password properties */
224         
225         ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
226
227         if (ret) {
228                 return NT_STATUS_INTERNAL_ERROR;
229         }
230         return NT_STATUS_OK;
231 }
232
233 static NTSTATUS samsync_ldb_handle_user(TALLOC_CTX *mem_ctx,
234                                         struct samsync_ldb_state *state,
235                                         enum netr_SamDatabaseID database,
236                                         struct netr_DELTA_ENUM *delta,
237                                         char **error_string) 
238 {
239         uint32_t rid = delta->delta_id_union.rid;
240         struct netr_DELTA_USER *user = delta->delta_union.user;
241         const char *container, *obj_class;
242         char *cn_name;
243         int cn_name_len;
244         const struct dom_sid *user_sid;
245         struct ldb_message *msg;
246         struct ldb_message **msgs;
247         struct ldb_message **remote_msgs = NULL;
248         int ret, i;
249         uint32_t acb;
250         BOOL add = False;
251         const char *attrs[] = { NULL };
252         /* we may change this to a global search, then fill in only the things not in ldap later */
253         const char *remote_attrs[] = { "userPrincipalName", "servicePrincipalName", 
254                                        "msDS-KeyVersionNumber", "objectGUID", NULL};
255
256         user_sid = dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid);
257         if (!user_sid) {
258                 return NT_STATUS_NO_MEMORY;
259         }
260
261         msg = ldb_msg_new(mem_ctx);
262         if (msg == NULL) {
263                 return NT_STATUS_NO_MEMORY;
264         }
265
266         msg->dn = NULL;
267         /* search for the user, by rid */
268         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database],
269                            &msgs, attrs, "(&(objectClass=user)(objectSid=%s))", 
270                            ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
271
272         if (ret == -1) {
273                 *error_string = talloc_asprintf(mem_ctx, "LDB for user %s failed: %s", 
274                                                 dom_sid_string(mem_ctx, user_sid),
275                                                 ldb_errstring(state->sam_ldb));
276                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
277         } else if (ret == 0) {
278                 add = True;
279         } else if (ret > 1) {
280                 *error_string = talloc_asprintf(mem_ctx, "More than one user with SID: %s in local LDB", 
281                                                 dom_sid_string(mem_ctx, user_sid));
282                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
283         } else {
284                 msg->dn = msgs[0]->dn;
285                 talloc_steal(msg, msgs[0]->dn);
286         }
287
288         /* and do the same on the remote database */
289         if (state->remote_ldb) {
290                 ret = gendb_search(state->remote_ldb, mem_ctx, state->base_dn[database],
291                                    &remote_msgs, remote_attrs, "(&(objectClass=user)(objectSid=%s))", 
292                                    ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
293                 
294                 if (ret == -1) {
295                         *error_string = talloc_asprintf(mem_ctx, "remote LDAP for user %s failed: %s", 
296                                                         dom_sid_string(mem_ctx, user_sid),
297                                                         ldb_errstring(state->remote_ldb));
298                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
299                 } else if (ret == 0) {
300                         *error_string = talloc_asprintf(mem_ctx, "User exists in samsync but not in remote LDAP domain! (base: %s, SID: %s)", 
301                                                         ldb_dn_get_linearized(state->base_dn[database]),
302                                                         dom_sid_string(mem_ctx, user_sid));
303                         return NT_STATUS_NO_SUCH_USER;
304                 } else if (ret > 1) {
305                         *error_string = talloc_asprintf(mem_ctx, "More than one user in remote LDAP domain with SID: %s", 
306                                                         dom_sid_string(mem_ctx, user_sid));
307                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
308                         
309                         /* Try to put things in the same location as the remote server */
310                 } else if (add) {
311                         msg->dn = remote_msgs[0]->dn;
312                         talloc_steal(msg, remote_msgs[0]->dn);
313                 }
314         }
315
316         cn_name   = talloc_strdup(mem_ctx, user->account_name.string);
317         NT_STATUS_HAVE_NO_MEMORY(cn_name);
318         cn_name_len = strlen(cn_name);
319
320 #define ADD_OR_DEL(type, attrib, field) do {                            \
321                 if (user->field) {                                      \
322                         samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
323                                                attrib, user->field);    \
324                 } else if (!add) {                                      \
325                         samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
326                                              attrib);                   \
327                 }                                                       \
328         } while (0);
329
330         ADD_OR_DEL(string, "samAccountName", account_name.string);
331         ADD_OR_DEL(string, "displayName", full_name.string);
332
333         if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
334                                   "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
335                 return NT_STATUS_NO_MEMORY; 
336         }
337
338         ADD_OR_DEL(uint, "primaryGroupID", primary_gid);
339         ADD_OR_DEL(string, "homeDirectory", home_directory.string);
340         ADD_OR_DEL(string, "homeDrive", home_drive.string);
341         ADD_OR_DEL(string, "scriptPath", logon_script.string);
342         ADD_OR_DEL(string, "description", description.string);
343         ADD_OR_DEL(string, "userWorkstations", workstations.string);
344
345         ADD_OR_DEL(uint64, "lastLogon", last_logon);
346         ADD_OR_DEL(uint64, "lastLogoff", last_logoff);
347
348         if (samdb_msg_add_logon_hours(state->sam_ldb, mem_ctx, msg, "logonHours", &user->logon_hours) != 0) { 
349                 return NT_STATUS_NO_MEMORY; 
350         }
351
352         ADD_OR_DEL(uint, "badPwdCount", bad_password_count);
353         ADD_OR_DEL(uint, "logonCount", logon_count);
354
355         ADD_OR_DEL(uint64, "pwdLastSet", last_password_change);
356         ADD_OR_DEL(uint64, "accountExpires", acct_expiry);
357         
358         if (samdb_msg_add_acct_flags(state->sam_ldb, mem_ctx, msg, 
359                                      "userAccountControl", user->acct_flags) != 0) { 
360                 return NT_STATUS_NO_MEMORY; 
361         } 
362         
363         if (!add) {
364                 /* Passwords.  Ensure there is no plaintext stored against
365                  * this entry, as we only have hashes */
366                 samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
367                                      "sambaPassword"); 
368         }
369         if (user->lm_password_present) {
370                 samdb_msg_add_hash(state->sam_ldb, mem_ctx, msg,  
371                                    "dBCSPwd", &user->lmpassword);
372         } else if (!add) {
373                 samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
374                                      "dBCSPwd"); 
375         }
376         if (user->nt_password_present) {
377                 samdb_msg_add_hash(state->sam_ldb, mem_ctx, msg,  
378                                    "unicodePwd", &user->ntpassword);
379         } else if (!add) {
380                 samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
381                                      "unicodePwd"); 
382         }
383             
384         ADD_OR_DEL(string, "comment", comment.string);
385         ADD_OR_DEL(string, "userParameters", parameters.string);
386         ADD_OR_DEL(uint, "countryCode", country_code);
387         ADD_OR_DEL(uint, "codePage", code_page);
388
389         ADD_OR_DEL(string, "profilePath", profile_path.string);
390
391 #undef ADD_OR_DEL
392
393         for (i=0; remote_attrs[i]; i++) {
394                 struct ldb_message_element *el = ldb_msg_find_element(remote_msgs[0], remote_attrs[i]);
395                 if (!el) {
396                         samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
397                                              remote_attrs[i]); 
398                 } else {
399                         ldb_msg_add(msg, el, LDB_FLAG_MOD_REPLACE);
400                 }
401         }
402
403         acb = user->acct_flags;
404         if (acb & (ACB_WSTRUST)) {
405                 cn_name[cn_name_len - 1] = '\0';
406                 container = "Computers";
407                 obj_class = "computer";
408                 
409         } else if (acb & ACB_SVRTRUST) {
410                 if (cn_name[cn_name_len - 1] != '$') {
411                         return NT_STATUS_FOOBAR;                
412                 }
413                 cn_name[cn_name_len - 1] = '\0';
414                 container = "Domain Controllers";
415                 obj_class = "computer";
416         } else {
417                 container = "Users";
418                 obj_class = "user";
419         }
420         if (add) {
421                 samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
422                                      "objectClass", obj_class);
423                 if (!msg->dn) {
424                         msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
425                         ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
426                         if (!msg->dn) {
427                                 return NT_STATUS_NO_MEMORY;             
428                         }
429                 }
430
431                 ret = samdb_add(state->sam_ldb, mem_ctx, msg);
432                 if (ret != 0) {
433                         struct ldb_dn *first_try_dn = msg->dn;
434                         /* Try again with the default DN */
435                         msg->dn = talloc_steal(msg, msgs[0]->dn);
436                         ret = samdb_add(state->sam_ldb, mem_ctx, msg);
437                         if (ret != 0) {
438                                 *error_string = talloc_asprintf(mem_ctx, "Failed to create user record.  Tried both %s and %s: %s",
439                                                                 ldb_dn_get_linearized(first_try_dn),
440                                                                 ldb_dn_get_linearized(msg->dn),
441                                                                 ldb_errstring(state->sam_ldb));
442                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
443                         }
444                 }
445         } else {
446                 ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
447                 if (ret != 0) {
448                         *error_string = talloc_asprintf(mem_ctx, "Failed to modify user record %s: %s",
449                                                         ldb_dn_get_linearized(msg->dn),
450                                                         ldb_errstring(state->sam_ldb));
451                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
452                 }
453         }
454
455         return NT_STATUS_OK;
456 }
457
458 static NTSTATUS samsync_ldb_delete_user(TALLOC_CTX *mem_ctx,
459                                         struct samsync_ldb_state *state,
460                                         enum netr_SamDatabaseID database,
461                                         struct netr_DELTA_ENUM *delta,
462                                         char **error_string) 
463 {
464         uint32_t rid = delta->delta_id_union.rid;
465         struct ldb_message **msgs;
466         int ret;
467         const char *attrs[] = { NULL };
468
469         /* search for the user, by rid */
470         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database],
471                            &msgs, attrs, "(&(objectClass=user)(objectSid=%s))", 
472                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
473
474         if (ret == -1) {
475                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
476                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
477         } else if (ret == 0) {
478                 return NT_STATUS_NO_SUCH_USER;
479         } else if (ret > 1) {
480                 *error_string = talloc_asprintf(mem_ctx, "More than one user with SID: %s", 
481                                                 dom_sid_string(mem_ctx, 
482                                                                dom_sid_add_rid(mem_ctx, 
483                                                                                state->dom_sid[database], 
484                                                                                rid)));
485                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
486         }
487
488         ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
489         if (ret != 0) {
490                 *error_string = talloc_asprintf(mem_ctx, "Failed to delete user record %s: %s",
491                                                 ldb_dn_get_linearized(msgs[0]->dn),
492                                                 ldb_errstring(state->sam_ldb));
493                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
494         }
495
496         return NT_STATUS_OK;
497 }
498
499 static NTSTATUS samsync_ldb_handle_group(TALLOC_CTX *mem_ctx,
500                                          struct samsync_ldb_state *state,
501                                          enum netr_SamDatabaseID database,
502                                          struct netr_DELTA_ENUM *delta,
503                                          char **error_string) 
504 {
505         uint32_t rid = delta->delta_id_union.rid;
506         struct netr_DELTA_GROUP *group = delta->delta_union.group;
507         const char *container, *obj_class;
508         const char *cn_name;
509
510         struct ldb_message *msg;
511         struct ldb_message **msgs;
512         int ret;
513         BOOL add = False;
514         const char *attrs[] = { NULL };
515
516         msg = ldb_msg_new(mem_ctx);
517         if (msg == NULL) {
518                 return NT_STATUS_NO_MEMORY;
519         }
520
521         /* search for the group, by rid */
522         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
523                            "(&(objectClass=group)(objectSid=%s))", 
524                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
525
526         if (ret == -1) {
527                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
528                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
529         } else if (ret == 0) {
530                 add = True;
531         } else if (ret > 1) {
532                 *error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
533                                                 dom_sid_string(mem_ctx, 
534                                                                dom_sid_add_rid(mem_ctx, 
535                                                                                state->dom_sid[database], 
536                                                                                rid)));
537                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
538         } else {
539                 msg->dn = talloc_steal(msg, msgs[0]->dn);
540         }
541
542         cn_name   = group->group_name.string;
543
544 #define ADD_OR_DEL(type, attrib, field) do {                            \
545                 if (group->field) {                                     \
546                         samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
547                                                attrib, group->field);   \
548                 } else if (!add) {                                      \
549                         samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
550                                              attrib);                   \
551                 }                                                       \
552         } while (0);
553
554         ADD_OR_DEL(string, "samAccountName", group_name.string);
555
556         if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
557                                   "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
558                 return NT_STATUS_NO_MEMORY; 
559         }
560
561         ADD_OR_DEL(string, "description", description.string);
562
563 #undef ADD_OR_DEL
564
565         container = "Users";
566         obj_class = "group";
567
568         if (add) {
569                 samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
570                                      "objectClass", obj_class);
571                 msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
572                 ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
573                 if (!msg->dn) {
574                         return NT_STATUS_NO_MEMORY;             
575                 }
576
577                 ret = samdb_add(state->sam_ldb, mem_ctx, msg);
578                 if (ret != 0) {
579                         *error_string = talloc_asprintf(mem_ctx, "Failed to create group record %s: %s",
580                                                         ldb_dn_get_linearized(msg->dn),
581                                                         ldb_errstring(state->sam_ldb));
582                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
583                 }
584         } else {
585                 ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
586                 if (ret != 0) {
587                         *error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
588                                                         ldb_dn_get_linearized(msg->dn),
589                                                         ldb_errstring(state->sam_ldb));
590                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
591                 }
592         }
593
594         return NT_STATUS_OK;
595 }
596
597 static NTSTATUS samsync_ldb_delete_group(TALLOC_CTX *mem_ctx,
598                                          struct samsync_ldb_state *state,
599                                          enum netr_SamDatabaseID database,
600                                          struct netr_DELTA_ENUM *delta,
601                                          char **error_string) 
602 {
603         uint32_t rid = delta->delta_id_union.rid;
604         struct ldb_message **msgs;
605         int ret;
606         const char *attrs[] = { NULL };
607
608         /* search for the group, by rid */
609         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
610                            "(&(objectClass=group)(objectSid=%s))", 
611                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
612
613         if (ret == -1) {
614                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
615                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
616         } else if (ret == 0) {
617                 return NT_STATUS_NO_SUCH_GROUP;
618         } else if (ret > 1) {
619                 *error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
620                                                 dom_sid_string(mem_ctx, 
621                                                                dom_sid_add_rid(mem_ctx, 
622                                                                                state->dom_sid[database], 
623                                                                                rid)));
624                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
625         }
626         
627         ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
628         if (ret != 0) {
629                 *error_string = talloc_asprintf(mem_ctx, "Failed to delete group record %s: %s",
630                                                 ldb_dn_get_linearized(msgs[0]->dn),
631                                                 ldb_errstring(state->sam_ldb));
632                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
633         }
634
635         return NT_STATUS_OK;
636 }
637
638 static NTSTATUS samsync_ldb_handle_group_member(TALLOC_CTX *mem_ctx,
639                                                 struct samsync_ldb_state *state,
640                                                 enum netr_SamDatabaseID database,
641                                                 struct netr_DELTA_ENUM *delta,
642                                                 char **error_string) 
643 {
644         uint32_t rid = delta->delta_id_union.rid;
645         struct netr_DELTA_GROUP_MEMBER *group_member = delta->delta_union.group_member;
646         struct ldb_message *msg;
647         struct ldb_message **msgs;
648         int ret;
649         const char *attrs[] = { NULL };
650         int i;
651
652         msg = ldb_msg_new(mem_ctx);
653         if (msg == NULL) {
654                 return NT_STATUS_NO_MEMORY;
655         }
656
657         /* search for the group, by rid */
658         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
659                            "(&(objectClass=group)(objectSid=%s))", 
660                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
661
662         if (ret == -1) {
663                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
664                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
665         } else if (ret == 0) {
666                 return NT_STATUS_NO_SUCH_GROUP;
667         } else if (ret > 1) {
668                 *error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
669                                                 dom_sid_string(mem_ctx, 
670                                                                dom_sid_add_rid(mem_ctx, 
671                                                                                state->dom_sid[database], 
672                                                                                rid)));
673                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
674         } else {
675                 msg->dn = talloc_steal(msg, msgs[0]->dn);
676         }
677         
678         talloc_free(msgs);
679
680         for (i=0; i<group_member->num_rids; i++) {
681                 /* search for the group, by rid */
682                 ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
683                                    "(&(objectClass=user)(objectSid=%s))", 
684                                    ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], group_member->rids[i]))); 
685                 
686                 if (ret == -1) {
687                         *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
688                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
689                 } else if (ret == 0) {
690                         return NT_STATUS_NO_SUCH_USER;
691                 } else if (ret > 1) {
692                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
693                 } else {
694                         samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "member", ldb_dn_alloc_linearized(mem_ctx, msgs[0]->dn));
695                 }
696                 
697                 talloc_free(msgs);
698         }
699         
700         ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
701         if (ret != 0) {
702                 *error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
703                                                 ldb_dn_get_linearized(msg->dn),
704                                                 ldb_errstring(state->sam_ldb));
705                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
706         }
707
708         return NT_STATUS_OK;
709 }
710
711 static NTSTATUS samsync_ldb_handle_alias(TALLOC_CTX *mem_ctx,
712                                          struct samsync_ldb_state *state,
713                                          enum netr_SamDatabaseID database,
714                                          struct netr_DELTA_ENUM *delta,
715                                          char **error_string) 
716 {
717         uint32_t rid = delta->delta_id_union.rid;
718         struct netr_DELTA_ALIAS *alias = delta->delta_union.alias;
719         const char *container, *obj_class;
720         const char *cn_name;
721
722         struct ldb_message *msg;
723         struct ldb_message **msgs;
724         int ret;
725         BOOL add = False;
726         const char *attrs[] = { NULL };
727
728         msg = ldb_msg_new(mem_ctx);
729         if (msg == NULL) {
730                 return NT_STATUS_NO_MEMORY;
731         }
732
733         /* search for the alias, by rid */
734         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
735                            "(&(objectClass=group)(objectSid=%s))", 
736                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
737
738         if (ret == -1) {
739                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
740                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
741         } else if (ret == 0) {
742                 add = True;
743         } else if (ret > 1) {
744                 *error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
745                                                 dom_sid_string(mem_ctx, 
746                                                                dom_sid_add_rid(mem_ctx, 
747                                                                                state->dom_sid[database], 
748                                                                                rid)));
749                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
750         } else {
751                 msg->dn = talloc_steal(mem_ctx, msgs[0]->dn);
752         }
753
754         cn_name   = alias->alias_name.string;
755
756 #define ADD_OR_DEL(type, attrib, field) do {                            \
757                 if (alias->field) {                                     \
758                         samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
759                                                attrib, alias->field);   \
760                 } else if (!add) {                                      \
761                         samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
762                                              attrib);                   \
763                 }                                                       \
764         } while (0);
765
766         ADD_OR_DEL(string, "samAccountName", alias_name.string);
767
768         if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
769                                   "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
770                 return NT_STATUS_NO_MEMORY; 
771         }
772
773         ADD_OR_DEL(string, "description", description.string);
774
775 #undef ADD_OR_DEL
776
777         samdb_msg_add_uint(state->sam_ldb, mem_ctx, msg, "groupType", 0x80000004);
778
779         container = "Users";
780         obj_class = "group";
781
782         if (add) {
783                 samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
784                                      "objectClass", obj_class);
785                 msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
786                 ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
787                 if (!msg->dn) {
788                         return NT_STATUS_NO_MEMORY;             
789                 }
790
791                 ret = samdb_add(state->sam_ldb, mem_ctx, msg);
792                 if (ret != 0) {
793                         *error_string = talloc_asprintf(mem_ctx, "Failed to create alias record %s: %s",
794                                                         ldb_dn_get_linearized(msg->dn),
795                                                         ldb_errstring(state->sam_ldb));
796                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
797                 }
798         } else {
799                 ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
800                 if (ret != 0) {
801                         *error_string = talloc_asprintf(mem_ctx, "Failed to modify alias record %s: %s",
802                                                         ldb_dn_get_linearized(msg->dn),
803                                                         ldb_errstring(state->sam_ldb));
804                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
805                 }
806         }
807
808         return NT_STATUS_OK;
809 }
810
811 static NTSTATUS samsync_ldb_delete_alias(TALLOC_CTX *mem_ctx,
812                                          struct samsync_ldb_state *state,
813                                          enum netr_SamDatabaseID database,
814                                          struct netr_DELTA_ENUM *delta,
815                                          char **error_string) 
816 {
817         uint32_t rid = delta->delta_id_union.rid;
818         struct ldb_message **msgs;
819         int ret;
820         const char *attrs[] = { NULL };
821
822         /* search for the alias, by rid */
823         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
824                            "(&(objectClass=group)(objectSid=%s))", 
825                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
826
827         if (ret == -1) {
828                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
829                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
830         } else if (ret == 0) {
831                 return NT_STATUS_NO_SUCH_ALIAS;
832         } else if (ret > 1) {
833                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
834         }
835
836         ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
837         if (ret != 0) {
838                 *error_string = talloc_asprintf(mem_ctx, "Failed to delete alias record %s: %s",
839                                                 ldb_dn_get_linearized(msgs[0]->dn),
840                                                 ldb_errstring(state->sam_ldb));
841                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
842         }
843
844         return NT_STATUS_OK;
845 }
846
847 static NTSTATUS samsync_ldb_handle_alias_member(TALLOC_CTX *mem_ctx,
848                                                 struct samsync_ldb_state *state,
849                                                 enum netr_SamDatabaseID database,
850                                                 struct netr_DELTA_ENUM *delta,
851                                                 char **error_string) 
852 {
853         uint32_t rid = delta->delta_id_union.rid;
854         struct netr_DELTA_ALIAS_MEMBER *alias_member = delta->delta_union.alias_member;
855         struct ldb_message *msg;
856         struct ldb_message **msgs;
857         int ret;
858         const char *attrs[] = { NULL };
859         int i;
860
861         msg = ldb_msg_new(mem_ctx);
862         if (msg == NULL) {
863                 return NT_STATUS_NO_MEMORY;
864         }
865
866         /* search for the alias, by rid */
867         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
868                            "(&(objectClass=group)(objectSid=%s))", 
869                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
870                 
871         if (ret == -1) {
872                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
873                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
874         } else if (ret == 0) {
875                 return NT_STATUS_NO_SUCH_GROUP;
876         } else if (ret > 1) {
877                 *error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
878                                                 dom_sid_string(mem_ctx, 
879                                                                dom_sid_add_rid(mem_ctx, 
880                                                                                state->dom_sid[database], 
881                                                                                rid)));
882                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
883         } else {
884                 msg->dn = talloc_steal(msg, msgs[0]->dn);
885         }
886         
887         talloc_free(msgs);
888
889         for (i=0; i<alias_member->sids.num_sids; i++) {
890                 struct ldb_dn *alias_member_dn;
891                 /* search for members, in the top basedn (normal users are builtin aliases) */
892                 ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
893                                    "(objectSid=%s)", 
894                                    ldap_encode_ndr_dom_sid(mem_ctx, alias_member->sids.sids[i].sid)); 
895
896                 if (ret == -1) {
897                         *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
898                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
899                 } else if (ret == 0) {
900                         NTSTATUS nt_status;
901                         nt_status = samsync_ldb_add_foreignSecurityPrincipal(mem_ctx, state,
902                                                                              alias_member->sids.sids[i].sid, 
903                                                                              &alias_member_dn, 
904                                                                              error_string);
905                         if (!NT_STATUS_IS_OK(nt_status)) {
906                                 return nt_status;
907                         }
908                 } else if (ret > 1) {
909                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
910                 } else {
911                         alias_member_dn = msgs[0]->dn;
912                 }
913                 samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "member", ldb_dn_alloc_linearized(mem_ctx, alias_member_dn));
914         
915                 talloc_free(msgs);
916         }
917
918         ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
919         if (ret != 0) {
920                 *error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
921                                                 ldb_dn_get_linearized(msg->dn),
922                                                 ldb_errstring(state->sam_ldb));
923                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
924         }
925
926         return NT_STATUS_OK;
927 }
928
929 static NTSTATUS samsync_ldb_handle_account(TALLOC_CTX *mem_ctx,
930                                            struct samsync_ldb_state *state,
931                                            enum netr_SamDatabaseID database,
932                                            struct netr_DELTA_ENUM *delta,
933                                            char **error_string) 
934 {
935         struct dom_sid *sid = delta->delta_id_union.sid;
936         struct netr_DELTA_ACCOUNT *account = delta->delta_union.account;
937
938         struct ldb_message *msg;
939         struct ldb_message **msgs;
940         struct ldb_dn *privilege_dn;
941         int ret;
942         const char *attrs[] = { NULL };
943         int i;
944
945         msg = ldb_msg_new(mem_ctx);
946         if (msg == NULL) {
947                 return NT_STATUS_NO_MEMORY;
948         }
949
950         /* search for the account, by sid, in the top basedn */
951         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
952                            "(objectSid=%s)", ldap_encode_ndr_dom_sid(mem_ctx, sid)); 
953
954         if (ret == -1) {
955                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
956                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
957         } else if (ret == 0) {
958                 NTSTATUS nt_status;
959                 nt_status = samsync_ldb_add_foreignSecurityPrincipal(mem_ctx, state,
960                                                                      sid,
961                                                                      &privilege_dn,
962                                                                      error_string);
963                 privilege_dn = talloc_steal(msg, privilege_dn);
964                 if (!NT_STATUS_IS_OK(nt_status)) {
965                         return nt_status;
966                 }
967         } else if (ret > 1) {
968                 *error_string = talloc_asprintf(mem_ctx, "More than one account with SID: %s", 
969                                                 dom_sid_string(mem_ctx, sid));
970                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
971         } else {
972                 privilege_dn = talloc_steal(msg, msgs[0]->dn);
973         }
974
975         msg->dn = privilege_dn;
976
977         for (i=0; i< account->privilege_entries; i++) {
978                 samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "privilege",
979                                      account->privilege_name[i].string);
980         }
981
982         ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
983         if (ret != 0) {
984                 *error_string = talloc_asprintf(mem_ctx, "Failed to modify privilege record %s",
985                                                 ldb_dn_get_linearized(msg->dn));
986                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
987         }
988
989         return NT_STATUS_OK;
990 }
991
992 static NTSTATUS samsync_ldb_delete_account(TALLOC_CTX *mem_ctx,
993                                            struct samsync_ldb_state *state,
994                                            enum netr_SamDatabaseID database,
995                                            struct netr_DELTA_ENUM *delta,
996                                            char **error_string) 
997 {
998         struct dom_sid *sid = delta->delta_id_union.sid;
999
1000         struct ldb_message *msg;
1001         struct ldb_message **msgs;
1002         int ret;
1003         const char *attrs[] = { NULL };
1004
1005         msg = ldb_msg_new(mem_ctx);
1006         if (msg == NULL) {
1007                 return NT_STATUS_NO_MEMORY;
1008         }
1009
1010         /* search for the account, by sid, in the top basedn */
1011         ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
1012                            "(objectSid=%s)", 
1013                            ldap_encode_ndr_dom_sid(mem_ctx, sid)); 
1014
1015         if (ret == -1) {
1016                 *error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
1017                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1018         } else if (ret == 0) {
1019                 return NT_STATUS_NO_SUCH_USER;
1020         } else if (ret > 1) {
1021                 *error_string = talloc_asprintf(mem_ctx, "More than one account with SID: %s", 
1022                                                 dom_sid_string(mem_ctx, sid));
1023                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1024         } else {
1025                 msg->dn = talloc_steal(msg, msgs[0]->dn);
1026         }
1027
1028         samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
1029                              "privilage"); 
1030
1031         ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
1032         if (ret != 0) {
1033                 *error_string = talloc_asprintf(mem_ctx, "Failed to modify privilege record %s",
1034                                                 ldb_dn_get_linearized(msg->dn));
1035                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1036         }
1037
1038         return NT_STATUS_OK;
1039 }
1040
1041 static NTSTATUS libnet_samsync_ldb_fn(TALLOC_CTX *mem_ctx,              
1042                                       void *private,                    
1043                                       enum netr_SamDatabaseID database,
1044                                       struct netr_DELTA_ENUM *delta,
1045                                       char **error_string)
1046 {
1047         NTSTATUS nt_status = NT_STATUS_OK;
1048         struct samsync_ldb_state *state = talloc_get_type(private, struct samsync_ldb_state);
1049
1050         *error_string = NULL;
1051         switch (delta->delta_type) {
1052         case NETR_DELTA_DOMAIN:
1053         {
1054                 nt_status = samsync_ldb_handle_domain(mem_ctx, 
1055                                                       state,
1056                                                       database,
1057                                                       delta,
1058                                                       error_string);
1059                 break;
1060         }
1061         case NETR_DELTA_USER:
1062         {
1063                 nt_status = samsync_ldb_handle_user(mem_ctx, 
1064                                                     state,
1065                                                     database,
1066                                                     delta,
1067                                                     error_string);
1068                 break;
1069         }
1070         case NETR_DELTA_DELETE_USER:
1071         {
1072                 nt_status = samsync_ldb_delete_user(mem_ctx, 
1073                                                     state,
1074                                                     database,
1075                                                     delta,
1076                                                     error_string);
1077                 break;
1078         }
1079         case NETR_DELTA_GROUP:
1080         {
1081                 nt_status = samsync_ldb_handle_group(mem_ctx, 
1082                                                      state,
1083                                                      database,
1084                                                      delta,
1085                                                      error_string);
1086                 break;
1087         }
1088         case NETR_DELTA_DELETE_GROUP:
1089         {
1090                 nt_status = samsync_ldb_delete_group(mem_ctx, 
1091                                                      state,
1092                                                      database,
1093                                                      delta,
1094                                                      error_string);
1095                 break;
1096         }
1097         case NETR_DELTA_GROUP_MEMBER:
1098         {
1099                 nt_status = samsync_ldb_handle_group_member(mem_ctx, 
1100                                                             state,
1101                                                             database,
1102                                                             delta,
1103                                                             error_string);
1104                 break;
1105         }
1106         case NETR_DELTA_ALIAS:
1107         {
1108                 nt_status = samsync_ldb_handle_alias(mem_ctx, 
1109                                                      state,
1110                                                      database,
1111                                                      delta,
1112                                                      error_string);
1113                 break;
1114         }
1115         case NETR_DELTA_DELETE_ALIAS:
1116         {
1117                 nt_status = samsync_ldb_delete_alias(mem_ctx, 
1118                                                      state,
1119                                                      database,
1120                                                      delta,
1121                                                      error_string);
1122                 break;
1123         }
1124         case NETR_DELTA_ALIAS_MEMBER:
1125         {
1126                 nt_status = samsync_ldb_handle_alias_member(mem_ctx, 
1127                                                             state,
1128                                                             database,
1129                                                             delta,
1130                                                             error_string);
1131                 break;
1132         }
1133         case NETR_DELTA_ACCOUNT:
1134         {
1135                 nt_status = samsync_ldb_handle_account(mem_ctx, 
1136                                                        state,
1137                                                        database,
1138                                                        delta,
1139                                                        error_string);
1140                 break;
1141         }
1142         case NETR_DELTA_DELETE_ACCOUNT:
1143         {
1144                 nt_status = samsync_ldb_delete_account(mem_ctx, 
1145                                                        state,
1146                                                        database,
1147                                                        delta,
1148                                                        error_string);
1149                 break;
1150         }
1151         default:
1152                 /* Can't dump them all right now */
1153                 break;
1154         }
1155         if (!NT_STATUS_IS_OK(nt_status) && !*error_string) {
1156                 *error_string = talloc_asprintf(mem_ctx, "Failed to handle samsync delta: %s", nt_errstr(nt_status));
1157         }
1158         return nt_status;
1159 }
1160
1161 static NTSTATUS libnet_samsync_ldb_init(TALLOC_CTX *mem_ctx,            
1162                                         void *private,
1163                                         struct libnet_SamSync_state *samsync_state,
1164                                         char **error_string)
1165 {
1166         struct samsync_ldb_state *state = talloc_get_type(private, struct samsync_ldb_state);
1167         const char *server = dcerpc_server_name(samsync_state->netlogon_pipe);
1168         char *ldap_url;
1169
1170         state->samsync_state = samsync_state;
1171
1172         ZERO_STRUCT(state->dom_sid);
1173         if (state->samsync_state->domain_sid) {
1174                 state->dom_sid[SAM_DATABASE_DOMAIN] = dom_sid_dup(state, state->samsync_state->domain_sid);
1175         }
1176
1177         state->dom_sid[SAM_DATABASE_BUILTIN] = dom_sid_parse_talloc(state, SID_BUILTIN);
1178
1179         if (state->samsync_state->realm) {
1180                 if (!server || !*server) {
1181                         /* huh?  how do we not have a server name?  */
1182                         *error_string = talloc_strdup(mem_ctx, "No DCE/RPC server name available.  How did we connect?");
1183                         return NT_STATUS_INVALID_PARAMETER;
1184                 }
1185                 ldap_url = talloc_asprintf(state, "ldap://%s", server);
1186                 
1187                 state->remote_ldb = ldb_wrap_connect(mem_ctx, ldap_url, 
1188                                                      NULL, state->samsync_state->machine_net_ctx->cred,
1189                                                      0, NULL);
1190                 if (!state->remote_ldb) {
1191                         *error_string = talloc_asprintf(mem_ctx, "Failed to connect to remote LDAP server at %s (used to extract additional data in SamSync replication)", ldap_url);
1192                         return NT_STATUS_NO_LOGON_SERVERS;
1193                 }
1194         } else {
1195                 state->remote_ldb = NULL;
1196         }
1197         return NT_STATUS_OK;
1198 }
1199
1200 NTSTATUS libnet_samsync_ldb(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_samsync_ldb *r)
1201 {
1202         NTSTATUS nt_status;
1203         struct libnet_SamSync r2;
1204         struct samsync_ldb_state *state = talloc(mem_ctx, struct samsync_ldb_state);
1205
1206         if (!state) {
1207                 return NT_STATUS_NO_MEMORY;
1208         }
1209
1210         state->secrets         = NULL;
1211         state->trusted_domains = NULL;
1212
1213         state->sam_ldb         = ldb_wrap_connect(mem_ctx, lp_sam_url(), 
1214                                                   r->in.session_info,
1215                                                   ctx->cred, 0, NULL);
1216
1217         r2.out.error_string    = NULL;
1218         r2.in.binding_string   = r->in.binding_string;
1219         r2.in.rid_crypt        = true;
1220         r2.in.init_fn          = libnet_samsync_ldb_init;
1221         r2.in.delta_fn         = libnet_samsync_ldb_fn;
1222         r2.in.fn_ctx           = state;
1223         r2.in.machine_account  = NULL; /* TODO:  Create a machine account, fill this in, and the delete it */
1224         nt_status              = libnet_SamSync_netlogon(ctx, state, &r2);
1225         r->out.error_string    = r2.out.error_string;
1226         talloc_steal(mem_ctx, r->out.error_string);
1227
1228         if (!NT_STATUS_IS_OK(nt_status)) {
1229                 talloc_free(state);
1230                 return nt_status;
1231         }
1232         talloc_free(state);
1233         return nt_status;
1234 }