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