r25920: ndr: change NTSTAUS into enum ndr_err_code (samba4 callers)
[kai/samba.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /* 
2    SAM ldb module
3
4    Copyright (C) Simo Sorce  2004
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6
7    * NOTICE: this module is NOT released under the GNU LGPL license as
8    * other ldb code. This module is release under the GNU GPL v2 or
9    * later license.
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 3 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, see <http://www.gnu.org/licenses/>.
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldb samldb module
29  *
30  *  Description: add embedded user/group creation functionality
31  *
32  *  Author: Simo Sorce
33  */
34
35 #include "includes.h"
36 #include "libcli/ldap/ldap.h"
37 #include "lib/ldb/include/ldb_errors.h"
38 #include "lib/ldb/include/ldb_private.h"
39 #include "dsdb/samdb/samdb.h"
40 #include "libcli/security/security.h"
41 #include "librpc/gen_ndr/ndr_security.h"
42 #include "db_wrap.h"
43
44 int samldb_notice_sid(struct ldb_module *module, 
45                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid);
46
47 static bool samldb_msg_add_sid(struct ldb_module *module, struct ldb_message *msg, const char *name, const struct dom_sid *sid)
48 {
49         struct ldb_val v;
50         enum ndr_err_code ndr_err;
51
52         ndr_err = ndr_push_struct_blob(&v, msg, sid,
53                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
54         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
55                 return false;
56         }
57         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
58 }
59
60 /*
61   allocate a new id, attempting to do it atomically
62   return 0 on failure, the id on success
63 */
64 static int samldb_set_next_rid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
65                                struct ldb_dn *dn, uint32_t old_id, uint32_t new_id)
66 {
67         struct ldb_message msg;
68         int ret;
69         struct ldb_val vals[2];
70         struct ldb_message_element els[2];
71
72         if (new_id == 0) {
73                 /* out of IDs ! */
74                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Are we out of valid IDs ?\n");
75                 return LDB_ERR_OPERATIONS_ERROR;
76         }
77
78         /* we do a delete and add as a single operation. That prevents
79            a race, in case we are not actually on a transaction db */
80         ZERO_STRUCT(msg);
81         msg.dn = ldb_dn_copy(mem_ctx, dn);
82         if (!msg.dn) {
83                 return LDB_ERR_OPERATIONS_ERROR;
84         }
85         msg.num_elements = 2;
86         msg.elements = els;
87
88         els[0].num_values = 1;
89         els[0].values = &vals[0];
90         els[0].flags = LDB_FLAG_MOD_DELETE;
91         els[0].name = talloc_strdup(mem_ctx, "nextRid");
92         if (!els[0].name) {
93                 return LDB_ERR_OPERATIONS_ERROR;
94         }
95
96         els[1].num_values = 1;
97         els[1].values = &vals[1];
98         els[1].flags = LDB_FLAG_MOD_ADD;
99         els[1].name = els[0].name;
100
101         vals[0].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", old_id);
102         if (!vals[0].data) {
103                 return LDB_ERR_OPERATIONS_ERROR;
104         }
105         vals[0].length = strlen((char *)vals[0].data);
106
107         vals[1].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", new_id);
108         if (!vals[1].data) {
109                 return LDB_ERR_OPERATIONS_ERROR;
110         }
111         vals[1].length = strlen((char *)vals[1].data);
112
113         ret = ldb_modify(ldb, &msg);
114         return ret;
115 }
116
117 /*
118   allocate a new id, attempting to do it atomically
119   return 0 on failure, the id on success
120 */
121 static int samldb_find_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
122                                 struct ldb_dn *dn, uint32_t *old_rid)
123 {
124         const char * const attrs[2] = { "nextRid", NULL };
125         struct ldb_result *res = NULL;
126         int ret;
127         const char *str;
128
129         ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, "nextRid=*", attrs, &res);
130         if (ret != LDB_SUCCESS) {
131                 return ret;
132         }
133         if (res->count != 1) {
134                 talloc_free(res);
135                 return LDB_ERR_OPERATIONS_ERROR;
136         }
137
138         str = ldb_msg_find_attr_as_string(res->msgs[0], "nextRid", NULL);
139         if (str == NULL) {
140                 ldb_asprintf_errstring(module->ldb,
141                                         "attribute nextRid not found in %s\n",
142                                         ldb_dn_get_linearized(dn));
143                 talloc_free(res);
144                 return LDB_ERR_OPERATIONS_ERROR;
145         }
146
147         *old_rid = strtol(str, NULL, 0);
148         talloc_free(res);
149         return LDB_SUCCESS;
150 }
151
152 static int samldb_allocate_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
153                                     struct ldb_dn *dn, const struct dom_sid *dom_sid, 
154                                     struct dom_sid **new_sid)
155 {
156         struct dom_sid *obj_sid;
157         uint32_t old_rid;
158         int ret;
159         
160         ret = samldb_find_next_rid(module, mem_ctx, dn, &old_rid);      
161         if (ret) {
162                 return ret;
163         }
164                 
165         /* return the new object sid */
166         obj_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid);
167                 
168         *new_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid + 1);
169         if (!*new_sid) {
170                 return LDB_ERR_OPERATIONS_ERROR;
171         }
172
173         ret = samldb_notice_sid(module, mem_ctx, *new_sid);
174         if (ret != 0) {
175                 /* gah, there are conflicting sids.
176                  * This is a critical situation it means that someone messed up with
177                  * the DB and nextRid is not returning free RIDs, report an error
178                  * and refuse to create any user until the problem is fixed */
179                 ldb_asprintf_errstring(module->ldb,
180                                         "Critical Error: unconsistent DB, unable to retireve an unique RID to generate a new SID: %s",
181                                         ldb_errstring(module->ldb));
182                 return ret;
183         }
184         return ret;
185 }
186
187 /* search the domain related to the provided dn
188    allocate a new RID for the domain
189    return the new sid string
190 */
191 static int samldb_get_new_sid(struct ldb_module *module, 
192                               TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
193                               struct dom_sid **sid)
194 {
195         const char * const attrs[2] = { "objectSid", NULL };
196         struct ldb_result *res = NULL;
197         struct ldb_dn *dom_dn;
198         int ret;
199         struct dom_sid *dom_sid;
200
201         /* get the domain component part of the provided dn */
202
203         dom_dn = samdb_search_for_parent_domain(module->ldb, mem_ctx, obj_dn);
204         if (dom_dn == NULL) {
205                 ldb_asprintf_errstring(module->ldb,
206                                         "Invalid dn (%s) not child of a domain object!\n",
207                                         ldb_dn_get_linearized(obj_dn));
208                 return LDB_ERR_CONSTRAINT_VIOLATION;
209         }
210
211         /* find the domain sid */
212
213         ret = ldb_search(module->ldb, dom_dn, LDB_SCOPE_BASE, "objectSid=*", attrs, &res);
214         if (ret != LDB_SUCCESS) {
215                 ldb_asprintf_errstring(module->ldb,
216                                         "samldb_get_new_sid: error retrieving domain sid from %s: %s!\n",
217                                         ldb_dn_get_linearized(dom_dn),
218                                         ldb_errstring(module->ldb));
219                 talloc_free(res);
220                 return ret;
221         }
222
223         if (res->count != 1) {
224                 ldb_asprintf_errstring(module->ldb,
225                                         "samldb_get_new_sid: error retrieving domain sid from %s: not found!\n",
226                                         ldb_dn_get_linearized(dom_dn));
227                 talloc_free(res);
228                 return LDB_ERR_CONSTRAINT_VIOLATION;
229         }
230
231         dom_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
232         if (dom_sid == NULL) {
233                 ldb_set_errstring(module->ldb, "samldb_get_new_sid: error parsing domain sid!\n");
234                 talloc_free(res);
235                 return LDB_ERR_CONSTRAINT_VIOLATION;
236         }
237
238         /* allocate a new Rid for the domain */
239         ret = samldb_allocate_next_rid(module, mem_ctx, dom_dn, dom_sid, sid);
240         if (ret != 0) {
241                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "Failed to increment nextRid of %s: %s\n", ldb_dn_get_linearized(dom_dn), ldb_errstring(module->ldb));
242                 talloc_free(res);
243                 return ret;
244         }
245
246         talloc_free(res);
247
248         return ret;
249 }
250
251 /* If we are adding new users/groups, we need to update the nextRid
252  * attribute to be 'above' all incoming users RIDs.  This tries to
253  * avoid clashes in future */
254
255 int samldb_notice_sid(struct ldb_module *module, 
256                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
257 {
258         int ret;
259         struct ldb_dn *dom_dn;
260         struct dom_sid *dom_sid;
261         const char *attrs[] = { NULL };
262         struct ldb_result *dom_res;
263         struct ldb_result *res;
264         uint32_t old_rid;
265
266         /* find if this SID already exists */
267         ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &res,
268                                  NULL, LDB_SCOPE_SUBTREE, attrs,
269                                  "(objectSid=%s)", ldap_encode_ndr_dom_sid(mem_ctx, sid));
270         if (ret == LDB_SUCCESS) {
271                 if (res->count > 0) {
272                         talloc_free(res);
273                         ldb_asprintf_errstring(module->ldb,
274                                                 "Attempt to add record with SID %s rejected,"
275                                                 " because this SID is already in the database",
276                                                 dom_sid_string(mem_ctx, sid));
277                         /* We have a duplicate SID, we must reject the add */
278                         return LDB_ERR_CONSTRAINT_VIOLATION;
279                 }
280                 talloc_free(res);
281         } else {
282                 ldb_asprintf_errstring(module->ldb,
283                                         "samldb_notice_sid: error searching to see if sid %s is in use: %s\n", 
284                                         dom_sid_string(mem_ctx, sid), 
285                                         ldb_errstring(module->ldb));
286                 return ret;
287         }
288
289         dom_sid = dom_sid_dup(mem_ctx, sid);
290         if (!dom_sid) {
291                 return LDB_ERR_OPERATIONS_ERROR;
292         }
293         /* get the domain component part of the provided SID */
294         dom_sid->num_auths--;
295
296         /* find the domain DN */
297         ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &dom_res,
298                                  NULL, LDB_SCOPE_SUBTREE, attrs,
299                                  "(&(objectSid=%s)(objectclass=domain))",
300                                  ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
301         if (ret == LDB_SUCCESS) {
302                 if (dom_res->count == 0) {
303                         talloc_free(dom_res);
304                         /* This isn't an operation on a domain we know about, so nothing to update */
305                         return LDB_SUCCESS;
306                 }
307
308                 if (dom_res->count > 1) {
309                         talloc_free(dom_res);
310                         ldb_asprintf_errstring(module->ldb,
311                                         "samldb_notice_sid: error retrieving domain from sid: duplicate (found %d) domain: %s!\n", 
312                                         dom_res->count, dom_sid_string(dom_res, dom_sid));
313                         return LDB_ERR_OPERATIONS_ERROR;
314                 }
315         } else {
316                 ldb_asprintf_errstring(module->ldb,
317                                         "samldb_notice_sid: error retrieving domain from sid: %s: %s\n", 
318                                         dom_sid_string(dom_res, dom_sid), 
319                                         ldb_errstring(module->ldb));
320                 return ret;
321         }
322
323         dom_dn = dom_res->msgs[0]->dn;
324
325         ret = samldb_find_next_rid(module, mem_ctx, 
326                                    dom_dn, &old_rid);
327         if (ret) {
328                 talloc_free(dom_res);
329                 return ret;
330         }
331
332         if (old_rid <= sid->sub_auths[sid->num_auths - 1]) {
333                 ret = samldb_set_next_rid(module->ldb, mem_ctx, dom_dn, old_rid, 
334                                           sid->sub_auths[sid->num_auths - 1] + 1);
335         }
336         talloc_free(dom_res);
337         return ret;
338 }
339
340 static int samldb_handle_sid(struct ldb_module *module, 
341                                          TALLOC_CTX *mem_ctx, struct ldb_message *msg2)
342 {
343         int ret;
344         
345         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg2, "objectSid");
346         if (sid == NULL) { 
347                 ret = samldb_get_new_sid(module, msg2, msg2->dn, &sid);
348                 if (ret != 0) {
349                         return ret;
350                 }
351
352                 if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
353                         talloc_free(sid);
354                         return LDB_ERR_OPERATIONS_ERROR;
355                 }
356                 talloc_free(sid);
357                 ret = LDB_SUCCESS;
358         } else {
359                 ret = samldb_notice_sid(module, msg2, sid);
360         }
361         return ret;
362 }
363
364 static char *samldb_generate_samAccountName(struct ldb_module *module, TALLOC_CTX *mem_ctx) 
365 {
366         char *name;
367         const char *attrs[] = { NULL };
368         struct ldb_message **msgs;
369         int ret;
370         
371         /* Format: $000000-000000000000 */
372         
373         do {
374                 name = talloc_asprintf(mem_ctx, "$%.6X-%.6X%.6X", (unsigned int)random(), (unsigned int)random(), (unsigned int)random());
375                 /* TODO: Figure out exactly what this is meant to conflict with */
376                 ret = gendb_search(module->ldb,
377                                    mem_ctx, NULL, &msgs, attrs,
378                                    "samAccountName=%s",
379                                    ldb_binary_encode_string(mem_ctx, name));
380                 if (ret == 0) {
381                         /* Great. There are no conflicting users/groups/etc */
382                         return name;
383                 } else if (ret == -1) {
384                         /* Bugger, there is a problem, and we don't know what it is until gendb_search improves */
385                         return NULL;
386                 } else {
387                         talloc_free(name);
388                         /* gah, there are conflicting sids, lets move around the loop again... */
389                 }
390         } while (1);
391 }
392
393 static int samldb_fill_group_object(struct ldb_module *module, const struct ldb_message *msg,
394                                                     struct ldb_message **ret_msg)
395 {
396         int ret;
397         const char *name;
398         struct ldb_message *msg2;
399         const char *rdn_name;
400         TALLOC_CTX *mem_ctx = talloc_new(msg);
401         const char *errstr;
402         if (!mem_ctx) {
403                 return LDB_ERR_OPERATIONS_ERROR;
404         }
405
406         /* build the new msg */
407         msg2 = ldb_msg_copy(mem_ctx, msg);
408         if (!msg2) {
409                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
410                 talloc_free(mem_ctx);
411                 return LDB_ERR_OPERATIONS_ERROR;
412         }
413
414         ret = samdb_copy_template(module->ldb, msg2, 
415                                   "group",
416                                   &errstr);
417         if (ret != 0) {
418                 
419                 talloc_free(mem_ctx);
420                 return ret;
421         }
422
423         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
424
425         if (strcasecmp(rdn_name, "cn") != 0) {
426                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: Bad RDN (%s) for group!\n", rdn_name);
427                 talloc_free(mem_ctx);
428                 return LDB_ERR_CONSTRAINT_VIOLATION;
429         }
430
431         /* Generate a random name, if no samAccountName was supplied */
432         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
433                 name = samldb_generate_samAccountName(module, mem_ctx);
434                 if (!name) {
435                         talloc_free(mem_ctx);
436                         return LDB_ERR_OPERATIONS_ERROR;
437                 }
438                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
439                 if (ret) {
440                         talloc_free(mem_ctx);
441                         return ret;
442                 }
443         }
444         
445         /* Manage SID allocation, conflicts etc */
446         ret = samldb_handle_sid(module, mem_ctx, msg2); 
447
448         if (ret == LDB_SUCCESS) {
449                 talloc_steal(msg, msg2);
450                 *ret_msg = msg2;
451         }
452         talloc_free(mem_ctx);
453         return ret;
454 }
455
456 static int samldb_fill_user_or_computer_object(struct ldb_module *module, const struct ldb_message *msg,
457                                                                struct ldb_message **ret_msg)
458 {
459         int ret;
460         char *name;
461         struct ldb_message *msg2;
462         const char *rdn_name;
463         TALLOC_CTX *mem_ctx = talloc_new(msg);
464         const char *errstr;
465         if (!mem_ctx) {
466                 return LDB_ERR_OPERATIONS_ERROR;
467         }
468
469         /* build the new msg */
470         msg2 = ldb_msg_copy(mem_ctx, msg);
471         if (!msg2) {
472                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
473                 talloc_free(mem_ctx);
474                 return LDB_ERR_OPERATIONS_ERROR;
475         }
476
477         if (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL) {
478
479                 ret = samdb_copy_template(module->ldb, msg2, 
480                                           "computer",
481                                           &errstr);
482                 if (ret) {
483                         ldb_asprintf_errstring(module->ldb, 
484                                                "samldb_fill_user_or_computer_object: "
485                                                "Error copying computer template: %s",
486                                                errstr);
487                         talloc_free(mem_ctx);
488                         return ret;
489                 }
490         } else {
491                 ret = samdb_copy_template(module->ldb, msg2, 
492                                           "user",
493                                           &errstr);
494                 if (ret) {
495                         ldb_asprintf_errstring(module->ldb, 
496                                                "samldb_fill_user_or_computer_object: Error copying user template: %s\n",
497                                                errstr);
498                         talloc_free(mem_ctx);
499                         return ret;
500                 }
501                 /* readd user objectclass */
502                 ret = samdb_find_or_add_value(module->ldb, msg2, "objectclass", "user");
503                 if (ret) {
504                         talloc_free(mem_ctx);
505                         return ret;
506                 }
507         }
508
509         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
510
511         if (strcasecmp(rdn_name, "cn") != 0) {
512                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for user/computer, should be CN=!\n", rdn_name);
513                 talloc_free(mem_ctx);
514                 return LDB_ERR_CONSTRAINT_VIOLATION;
515         }
516
517         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
518                 name = samldb_generate_samAccountName(module, mem_ctx);
519                 if (!name) {
520                         talloc_free(mem_ctx);
521                         return LDB_ERR_OPERATIONS_ERROR;
522                 }
523                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
524                 if (ret) {
525                         talloc_free(mem_ctx);
526                         return ret;
527                 }
528         }
529
530         /*
531           TODO: useraccountcontrol: setting value 0 gives 0x200 for users
532         */
533
534         /* Manage SID allocation, conflicts etc */
535         ret = samldb_handle_sid(module, mem_ctx, msg2); 
536
537         /* TODO: objectCategory, userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogoff, lastLogon, pwdLastSet, primaryGroupID, accountExpires, logonCount */
538
539         if (ret == 0) {
540                 *ret_msg = msg2;
541                 talloc_steal(msg, msg2);
542         }
543         talloc_free(mem_ctx);
544         return ret;
545 }
546         
547 static int samldb_fill_foreignSecurityPrincipal_object(struct ldb_module *module, const struct ldb_message *msg, 
548                                                        struct ldb_message **ret_msg)
549 {
550         struct ldb_message *msg2;
551         const char *rdn_name;
552         struct dom_sid *dom_sid;
553         struct dom_sid *sid;
554         const char *dom_attrs[] = { "name", NULL };
555         struct ldb_message **dom_msgs;
556         const char *errstr;
557         int ret;
558
559         TALLOC_CTX *mem_ctx = talloc_new(msg);
560         if (!mem_ctx) {
561                 return LDB_ERR_OPERATIONS_ERROR;
562         }
563
564         /* build the new msg */
565         msg2 = ldb_msg_copy(mem_ctx, msg);
566         if (!msg2) {
567                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_foreignSecurityPrincipal_object: ldb_msg_copy failed!\n");
568                 talloc_free(mem_ctx);
569                 return LDB_ERR_OPERATIONS_ERROR;
570         }
571
572         ret = samdb_copy_template(module->ldb, msg2, 
573                                   "ForeignSecurityPrincipal",
574                                   &errstr);
575         if (ret != 0) {
576                 ldb_asprintf_errstring(module->ldb, 
577                                        "samldb_fill_foreignSecurityPrincipal_object: "
578                                        "Error copying template: %s",
579                                     errstr);
580                 talloc_free(mem_ctx);
581                 return ret;
582         }
583
584         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
585
586         if (strcasecmp(rdn_name, "cn") != 0) {
587                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for ForeignSecurityPrincipal, should be CN=!", rdn_name);
588                 talloc_free(mem_ctx);
589                 return LDB_ERR_CONSTRAINT_VIOLATION;
590         }
591
592         sid = samdb_result_dom_sid(msg2, msg, "objectSid");
593         if (!sid) {
594                 /* Slightly different for the foreign sids.  We don't want
595                  * domain SIDs ending up there, it would cause all sorts of
596                  * pain */
597
598                 sid = dom_sid_parse_talloc(msg2, (const char *)ldb_dn_get_rdn_val(msg2->dn)->data);
599                 if (!sid) {
600                         ldb_set_errstring(module->ldb, "No valid found SID in ForeignSecurityPrincipal CN!");
601                         talloc_free(mem_ctx);
602                         return LDB_ERR_CONSTRAINT_VIOLATION;
603                 }
604
605                 if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
606                         talloc_free(sid);
607                         return LDB_ERR_OPERATIONS_ERROR;
608                 }
609
610                 dom_sid = dom_sid_dup(mem_ctx, sid);
611                 if (!dom_sid) {
612                         talloc_free(mem_ctx);
613                         return LDB_ERR_OPERATIONS_ERROR;
614                 }
615                 /* get the domain component part of the provided SID */
616                 dom_sid->num_auths--;
617
618                 /* find the domain DN */
619
620                 ret = gendb_search(module->ldb,
621                                    mem_ctx, NULL, &dom_msgs, dom_attrs,
622                                    "(&(objectSid=%s)(objectclass=domain))",
623                                    ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
624                 if (ret >= 1) {
625                         /* We don't really like the idea of foreign sids that are not foreign, but it happens */
626                         const char *name = samdb_result_string(dom_msgs[0], "name", NULL);
627                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "NOTE (strange but valid): Adding foreign SID record with SID %s, but this domian (%s) is already in the database", 
628                                   dom_sid_string(mem_ctx, sid), name); 
629                 } else if (ret == -1) {
630                         ldb_asprintf_errstring(module->ldb,
631                                                 "samldb_fill_foreignSecurityPrincipal_object: error searching for a domain with this sid: %s\n", 
632                                                 dom_sid_string(mem_ctx, dom_sid));
633                         talloc_free(dom_msgs);
634                         return LDB_ERR_OPERATIONS_ERROR;
635                 }
636         }
637
638         /* This isn't an operation on a domain we know about, so just
639          * check for the SID, looking for duplicates via the common
640          * code */
641         ret = samldb_notice_sid(module, msg2, sid);
642         if (ret == 0) {
643                 talloc_steal(msg, msg2);
644                 *ret_msg = msg2;
645         }
646         
647         return ret;
648 }
649
650 /* add_record */
651
652 /*
653  * FIXME
654  *
655  * Actually this module is not async at all as it does a number of sync searches
656  * in the process. It still to be decided how to deal with it properly so it is
657  * left SYNC for now until we think of a good solution.
658  */
659
660 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
661 {
662         const struct ldb_message *msg = req->op.add.message;
663         struct ldb_message *msg2 = NULL;
664         struct ldb_request *down_req;
665         int ret;
666
667         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "samldb_add_record\n");
668
669         if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
670                 return ldb_next_request(module, req);
671         }
672
673         /* is user or computer? */
674         if ((samdb_find_attribute(module->ldb, msg, "objectclass", "user") != NULL) ||
675             (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL)) {
676                 /*  add all relevant missing objects */
677                 ret = samldb_fill_user_or_computer_object(module, msg, &msg2);
678                 if (ret) {
679                         return ret;
680                 }
681         }
682
683         /* is group? add all relevant missing objects */
684         if ( ! msg2 ) {
685                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "group") != NULL) {
686                         ret = samldb_fill_group_object(module, msg, &msg2);
687                         if (ret) {
688                                 return ret;
689                         }
690                 }
691         }
692
693         /* perhaps a foreignSecurityPrincipal? */
694         if ( ! msg2 ) {
695                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "foreignSecurityPrincipal") != NULL) {
696                         ret = samldb_fill_foreignSecurityPrincipal_object(module, msg, &msg2);
697                         if (ret) {
698                                 return ret;
699                         }
700                 }
701         }
702
703         if (msg2 == NULL) {
704                 return ldb_next_request(module, req);
705         }
706
707         down_req = talloc(req, struct ldb_request);
708         if (down_req == NULL) {
709                 return LDB_ERR_OPERATIONS_ERROR;
710         }
711
712         *down_req = *req;
713         
714         down_req->op.add.message = talloc_steal(down_req, msg2);
715
716         ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
717
718         /* go on with the call chain */
719         ret = ldb_next_request(module, down_req);
720
721         /* do not free down_req as the call results may be linked to it,
722          * it will be freed when the upper level request get freed */
723         if (ret == LDB_SUCCESS) {
724                 req->handle = down_req->handle;
725         }
726
727         return ret;
728 }
729
730 static int samldb_init(struct ldb_module *module)
731 {
732         return ldb_next_init(module);
733 }
734
735 static const struct ldb_module_ops samldb_ops = {
736         .name          = "samldb",
737         .init_context  = samldb_init,
738         .add           = samldb_add,
739 };
740
741
742 int samldb_module_init(void)
743 {
744         return ldb_register_module(&samldb_ops);
745 }