r17516: Change helper function names to make more clear what they are meant to do
[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 2 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26 /*
27  *  Name: ldb
28  *
29  *  Component: ldb samldb module
30  *
31  *  Description: add embedded user/group creation functionality
32  *
33  *  Author: Simo Sorce
34  */
35
36 #include "includes.h"
37 #include "libcli/ldap/ldap.h"
38 #include "lib/ldb/include/ldb_errors.h"
39 #include "lib/ldb/include/ldb_private.h"
40 #include "dsdb/samdb/samdb.h"
41 #include "libcli/security/security.h"
42 #include "librpc/gen_ndr/ndr_security.h"
43 #include "db_wrap.h"
44
45 int samldb_notice_sid(struct ldb_module *module, 
46                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid);
47
48 static BOOL samldb_msg_add_sid(struct ldb_module *module, struct ldb_message *msg, const char *name, const struct dom_sid *sid)
49 {
50         struct ldb_val v;
51         NTSTATUS status;
52         status = ndr_push_struct_blob(&v, msg, sid, 
53                                       (ndr_push_flags_fn_t)ndr_push_dom_sid);
54         if (!NT_STATUS_IS_OK(status)) {
55                 return -1;
56         }
57         return (ldb_msg_add_value(msg, name, &v) == 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                                const 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                                 const 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         talloc_steal(mem_ctx, res);
134         if (res->count != 1) {
135                 talloc_free(res);
136                 return LDB_ERR_OPERATIONS_ERROR;
137         }
138
139         str = ldb_msg_find_attr_as_string(res->msgs[0], "nextRid", NULL);
140         if (str == NULL) {
141                 ldb_asprintf_errstring(module->ldb,
142                                         "attribute nextRid not found in %s\n",
143                                         ldb_dn_linearize(res, dn));
144                 talloc_free(res);
145                 return LDB_ERR_OPERATIONS_ERROR;
146         }
147
148         *old_rid = strtol(str, NULL, 0);
149         talloc_free(res);
150         return LDB_SUCCESS;
151 }
152
153 static int samldb_allocate_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
154                                     const struct ldb_dn *dn, const struct dom_sid *dom_sid, 
155                                     struct dom_sid **new_sid)
156 {
157         struct dom_sid *obj_sid;
158         uint32_t old_rid;
159         int ret;
160         
161         ret = samldb_find_next_rid(module, mem_ctx, dn, &old_rid);      
162         if (ret) {
163                 return ret;
164         }
165                 
166         /* return the new object sid */
167         obj_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid);
168                 
169         *new_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid + 1);
170         if (!*new_sid) {
171                 return LDB_ERR_OPERATIONS_ERROR;
172         }
173
174         ret = samldb_notice_sid(module, mem_ctx, *new_sid);
175         if (ret != 0) {
176                 /* gah, there are conflicting sids.
177                  * This is a critical situation it means that someone messed up with
178                  * the DB and nextRid is not returning free RIDs, report an error
179                  * and refuse to create any user until the problem is fixed */
180                 ldb_asprintf_errstring(module->ldb,
181                                         "Critical Error: unconsistent DB, unable to retireve an unique RID to generate a new SID: %s",
182                                         ldb_errstring(module->ldb));
183                 return ret;
184         }
185         return ret;
186 }
187
188 /* Find a domain object in the parents of a particular DN.  */
189 static struct ldb_dn *samldb_search_domain(struct ldb_module *module, TALLOC_CTX *mem_ctx, const struct ldb_dn *dn)
190 {
191         TALLOC_CTX *local_ctx;
192         struct ldb_dn *sdn;
193         struct ldb_result *res = NULL;
194         int ret = 0;
195         const char *attrs[] = { NULL };
196
197         local_ctx = talloc_new(mem_ctx);
198         if (local_ctx == NULL) return NULL;
199
200         sdn = ldb_dn_copy(local_ctx, dn);
201         do {
202                 ret = ldb_search(module->ldb, sdn, LDB_SCOPE_BASE, 
203                                  "(|(objectClass=domain)(objectClass=builtinDomain))", attrs, &res);
204                 talloc_steal(local_ctx, res);
205                 if (ret == LDB_SUCCESS && res->count == 1)
206                         break;
207         } while ((sdn = ldb_dn_get_parent(local_ctx, sdn)));
208
209         if (ret != LDB_SUCCESS || res->count != 1) {
210                 talloc_free(local_ctx);
211                 return NULL;
212         }
213
214         talloc_steal(mem_ctx, sdn);
215         talloc_free(local_ctx);
216
217         return sdn;
218 }
219
220 /* search the domain related to the provided dn
221    allocate a new RID for the domain
222    return the new sid string
223 */
224 static int samldb_get_new_sid(struct ldb_module *module, 
225                               TALLOC_CTX *mem_ctx, const struct ldb_dn *obj_dn,
226                               struct dom_sid **sid)
227 {
228         const char * const attrs[2] = { "objectSid", NULL };
229         struct ldb_result *res = NULL;
230         const struct ldb_dn *dom_dn;
231         int ret;
232         struct dom_sid *dom_sid;
233
234         /* get the domain component part of the provided dn */
235
236         dom_dn = samldb_search_domain(module, mem_ctx, obj_dn);
237         if (dom_dn == NULL) {
238                 ldb_asprintf_errstring(module->ldb,
239                                         "Invalid dn (%s) not child of a domain object!\n",
240                                         ldb_dn_linearize(mem_ctx, obj_dn));
241                 return LDB_ERR_CONSTRAINT_VIOLATION;
242         }
243
244         /* find the domain sid */
245
246         ret = ldb_search(module->ldb, dom_dn, LDB_SCOPE_BASE, "objectSid=*", attrs, &res);
247         if (ret != LDB_SUCCESS) {
248                 ldb_asprintf_errstring(module->ldb,
249                                         "samldb_get_new_sid: error retrieving domain sid from %s: %s!\n",
250                                         ldb_dn_linearize(mem_ctx, dom_dn),
251                                         ldb_errstring(module->ldb));
252                 talloc_free(res);
253                 return ret;
254         }
255
256         if (res->count != 1) {
257                 ldb_asprintf_errstring(module->ldb,
258                                         "samldb_get_new_sid: error retrieving domain sid from %s: not found!\n",
259                                         ldb_dn_linearize(mem_ctx, dom_dn));
260                 return LDB_ERR_CONSTRAINT_VIOLATION;
261         }
262
263         dom_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
264         if (dom_sid == NULL) {
265                 ldb_set_errstring(module->ldb, "samldb_get_new_sid: error parsing domain sid!\n");
266                 talloc_free(res);
267                 return LDB_ERR_CONSTRAINT_VIOLATION;
268         }
269
270         /* allocate a new Rid for the domain */
271         ret = samldb_allocate_next_rid(module, mem_ctx, dom_dn, dom_sid, sid);
272         if (ret != 0) {
273                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "Failed to increment nextRid of %s: %s\n", ldb_dn_linearize(mem_ctx, dom_dn), ldb_errstring(module->ldb));
274                 talloc_free(res);
275                 return ret;
276         }
277
278         talloc_free(res);
279
280         return ret;
281 }
282
283 /* If we are adding new users/groups, we need to update the nextRid
284  * attribute to be 'above' all incoming users RIDs.  This tries to
285  * avoid clashes in future */
286
287 int samldb_notice_sid(struct ldb_module *module, 
288                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
289 {
290         int ret;
291         struct ldb_dn *dom_dn;
292         struct dom_sid *dom_sid;
293         const char *attrs[] = { NULL };
294         struct ldb_result *dom_res;
295         struct ldb_result *res;
296         uint32_t old_rid;
297         char *filter;
298
299         /* find if this SID already exists */
300
301         filter = talloc_asprintf(mem_ctx, "(objectSid=%s)",
302                                  ldap_encode_ndr_dom_sid(mem_ctx, sid));
303
304         ret = ldb_search(module->ldb, samdb_base_dn(mem_ctx), LDB_SCOPE_SUBTREE, filter, attrs, &res);
305         if (ret == LDB_SUCCESS) {
306                 if (res->count > 0) {
307                         talloc_free(res);
308                         ldb_asprintf_errstring(module->ldb,
309                                                 "Attempt to add record with SID %s rejected,"
310                                                 " because this SID is already in the database",
311                                                 dom_sid_string(mem_ctx, sid));
312                         /* We have a duplicate SID, we must reject the add */
313                         return LDB_ERR_CONSTRAINT_VIOLATION;
314                 }
315                 talloc_free(res);
316         } else {
317                 ldb_asprintf_errstring(module->ldb,
318                                         "samldb_notice_sid: error searching to see if sid %s is in use: %s\n", 
319                                         dom_sid_string(mem_ctx, sid), 
320                                         ldb_errstring(module->ldb));
321                 return ret;
322         }
323
324         dom_sid = dom_sid_dup(mem_ctx, sid);
325         if (!dom_sid) {
326                 return LDB_ERR_OPERATIONS_ERROR;
327         }
328         /* get the domain component part of the provided SID */
329         dom_sid->num_auths--;
330
331         /* find the domain DN */
332         
333         filter = talloc_asprintf(mem_ctx, "(&(objectSid=%s)(objectclass=domain))",
334                                  ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
335
336         ret = ldb_search(module->ldb, samdb_base_dn(mem_ctx), LDB_SCOPE_SUBTREE, filter, attrs, &dom_res);
337         if (ret == LDB_SUCCESS) {
338                 talloc_steal(mem_ctx, dom_res);
339                 if (dom_res->count == 0) {
340                         talloc_free(dom_res);
341                         /* This isn't an operation on a domain we know about, so nothing to update */
342                         return LDB_SUCCESS;
343                 }
344
345                 if (dom_res->count > 1) {
346                         talloc_free(dom_res);
347                         ldb_asprintf_errstring(module->ldb,
348                                         "samldb_notice_sid: error retrieving domain from sid: duplicate (found %d) domain: %s!\n", 
349                                         dom_res->count, dom_sid_string(dom_res, dom_sid));
350                         return LDB_ERR_OPERATIONS_ERROR;
351                 }
352         } else {
353                 ldb_asprintf_errstring(module->ldb,
354                                         "samldb_notice_sid: error retrieving domain from sid: %s: %s\n", 
355                                         dom_sid_string(dom_res, dom_sid), 
356                                         ldb_errstring(module->ldb));
357                 return ret;
358         }
359
360         dom_dn = dom_res->msgs[0]->dn;
361
362         ret = samldb_find_next_rid(module, mem_ctx, 
363                                    dom_dn, &old_rid);
364         if (ret) {
365                 talloc_free(dom_res);
366                 return ret;
367         }
368
369         if (old_rid <= sid->sub_auths[sid->num_auths - 1]) {
370                 ret = samldb_set_next_rid(module->ldb, mem_ctx, dom_dn, old_rid, 
371                                           sid->sub_auths[sid->num_auths - 1] + 1);
372         }
373         talloc_free(dom_res);
374         return ret;
375 }
376
377 static int samldb_handle_sid(struct ldb_module *module, 
378                                          TALLOC_CTX *mem_ctx, struct ldb_message *msg2)
379 {
380         int ret;
381         
382         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg2, "objectSid");
383         if (sid == NULL) { 
384                 ret = samldb_get_new_sid(module, msg2, msg2->dn, &sid);
385                 if (ret != 0) {
386                         return ret;
387                 }
388
389                 if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
390                         talloc_free(sid);
391                         return LDB_ERR_OPERATIONS_ERROR;
392                 }
393                 talloc_free(sid);
394                 ret = LDB_SUCCESS;
395         } else {
396                 ret = samldb_notice_sid(module, msg2, sid);
397         }
398         return ret;
399 }
400
401 static char *samldb_generate_samAccountName(struct ldb_module *module, TALLOC_CTX *mem_ctx) 
402 {
403         char *name;
404         const char *attrs[] = { NULL };
405         struct ldb_message **msgs;
406         int ret;
407         
408         /* Format: $000000-000000000000 */
409         
410         do {
411                 name = talloc_asprintf(mem_ctx, "$%.6X-%.6X%.6X", (unsigned int)random(), (unsigned int)random(), (unsigned int)random());
412                 /* TODO: Figure out exactly what this is meant to conflict with */
413                 ret = gendb_search(module->ldb,
414                                    mem_ctx, NULL, &msgs, attrs,
415                                    "samAccountName=%s",
416                                    ldb_binary_encode_string(mem_ctx, name));
417                 if (ret == 0) {
418                         /* Great. There are no conflicting users/groups/etc */
419                         return name;
420                 } else if (ret == -1) {
421                         /* Bugger, there is a problem, and we don't know what it is until gendb_search improves */
422                         return NULL;
423                 } else {
424                         talloc_free(name);
425                         /* gah, there are conflicting sids, lets move around the loop again... */
426                 }
427         } while (1);
428 }
429
430 static int samldb_fill_group_object(struct ldb_module *module, const struct ldb_message *msg,
431                                                     struct ldb_message **ret_msg)
432 {
433         int ret;
434         const char *name;
435         struct ldb_message *msg2;
436         struct ldb_dn_component *rdn;
437         TALLOC_CTX *mem_ctx = talloc_new(msg);
438         if (!mem_ctx) {
439                 return LDB_ERR_OPERATIONS_ERROR;
440         }
441
442         /* build the new msg */
443         msg2 = ldb_msg_copy(mem_ctx, msg);
444         if (!msg2) {
445                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
446                 talloc_free(mem_ctx);
447                 return LDB_ERR_OPERATIONS_ERROR;
448         }
449
450         ret = samdb_copy_template(module->ldb, msg2, "(&(CN=TemplateGroup)(objectclass=groupTemplate))");
451         if (ret != 0) {
452                 talloc_free(mem_ctx);
453                 return ret;
454         }
455
456         rdn = ldb_dn_get_rdn(msg2, msg2->dn);
457
458         if (strcasecmp(rdn->name, "cn") != 0) {
459                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: Bad RDN (%s) for group!\n", rdn->name);
460                 talloc_free(mem_ctx);
461                 return LDB_ERR_CONSTRAINT_VIOLATION;
462         }
463
464         /* Generate a random name, if no samAccountName was supplied */
465         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
466                 name = samldb_generate_samAccountName(module, mem_ctx);
467                 if (!name) {
468                         talloc_free(mem_ctx);
469                         return LDB_ERR_OPERATIONS_ERROR;
470                 }
471                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
472                 if (ret) {
473                         talloc_free(mem_ctx);
474                         return ret;
475                 }
476         }
477         
478         /* Manage SID allocation, conflicts etc */
479         ret = samldb_handle_sid(module, mem_ctx, msg2); 
480
481         if (ret == LDB_SUCCESS) {
482                 talloc_steal(msg, msg2);
483                 *ret_msg = msg2;
484         }
485         talloc_free(mem_ctx);
486         return ret;
487 }
488
489 static int samldb_fill_user_or_computer_object(struct ldb_module *module, const struct ldb_message *msg,
490                                                                struct ldb_message **ret_msg)
491 {
492         int ret;
493         char *name;
494         struct ldb_message *msg2;
495         struct ldb_dn_component *rdn;
496         TALLOC_CTX *mem_ctx = talloc_new(msg);
497         if (!mem_ctx) {
498                 return LDB_ERR_OPERATIONS_ERROR;
499         }
500
501         /* build the new msg */
502         msg2 = ldb_msg_copy(mem_ctx, msg);
503         if (!msg2) {
504                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
505                 talloc_free(mem_ctx);
506                 return LDB_ERR_OPERATIONS_ERROR;
507         }
508
509         if (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL) {
510
511                 ret = samdb_copy_template(module->ldb, msg2, "(&(CN=TemplateComputer)(objectclass=userTemplate))");
512                 if (ret) {
513                         ldb_debug(module->ldb, LDB_DEBUG_WARNING, "samldb_fill_user_or_computer_object: Error copying computer template!\n");
514                         talloc_free(mem_ctx);
515                         return ret;
516                 }
517
518                 /* readd user and then computer objectclasses */
519                 ret = samdb_find_or_add_value(module->ldb, msg2, "objectclass", "user");
520                 if (ret) {
521                         talloc_free(mem_ctx);
522                         return ret;
523                 }
524                 ret = samdb_find_or_add_value(module->ldb, msg2, "objectclass", "computer");
525                 if (ret) {
526                         talloc_free(mem_ctx);
527                         return ret;
528                 }
529                 
530         } else {
531                 ret = samdb_copy_template(module->ldb, msg2, "(&(CN=TemplateUser)(objectclass=userTemplate))");
532                 if (ret) {
533                         ldb_debug(module->ldb, LDB_DEBUG_WARNING, "samldb_fill_user_or_computer_object: Error copying user template!\n");
534                         talloc_free(mem_ctx);
535                         return ret;
536                 }
537                 /* readd user objectclass */
538                 ret = samdb_find_or_add_value(module->ldb, msg2, "objectclass", "user");
539                 if (ret) {
540                         talloc_free(mem_ctx);
541                         return ret;
542                 }
543         }
544
545         rdn = ldb_dn_get_rdn(msg2, msg2->dn);
546
547         if (strcasecmp(rdn->name, "cn") != 0) {
548                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for user/computer, should be CN=!\n", rdn->name);
549                 talloc_free(mem_ctx);
550                 return LDB_ERR_CONSTRAINT_VIOLATION;
551         }
552
553         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
554                 name = samldb_generate_samAccountName(module, mem_ctx);
555                 if (!name) {
556                         talloc_free(mem_ctx);
557                         return LDB_ERR_OPERATIONS_ERROR;
558                 }
559                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
560                 if (ret) {
561                         talloc_free(mem_ctx);
562                         return ret;
563                 }
564         }
565
566         /*
567           TODO: useraccountcontrol: setting value 0 gives 0x200 for users
568         */
569
570         /* Manage SID allocation, conflicts etc */
571         ret = samldb_handle_sid(module, mem_ctx, msg2); 
572
573         /* TODO: objectCategory, userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogoff, lastLogon, pwdLastSet, primaryGroupID, accountExpires, logonCount */
574
575         if (ret == 0) {
576                 *ret_msg = msg2;
577                 talloc_steal(msg, msg2);
578         }
579         talloc_free(mem_ctx);
580         return ret;
581 }
582         
583 static int samldb_fill_foreignSecurityPrincipal_object(struct ldb_module *module, const struct ldb_message *msg, 
584                                                                        struct ldb_message **ret_msg)
585 {
586         struct ldb_message *msg2;
587         struct ldb_dn_component *rdn;
588         struct dom_sid *dom_sid;
589         struct dom_sid *sid;
590         const char *dom_attrs[] = { "name", NULL };
591         struct ldb_message **dom_msgs;
592         int ret;
593
594         TALLOC_CTX *mem_ctx = talloc_new(msg);
595         if (!mem_ctx) {
596                 return LDB_ERR_OPERATIONS_ERROR;
597         }
598
599         /* build the new msg */
600         msg2 = ldb_msg_copy(mem_ctx, msg);
601         if (!msg2) {
602                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_foreignSecurityPrincpal_object: ldb_msg_copy failed!\n");
603                 talloc_free(mem_ctx);
604                 return LDB_ERR_OPERATIONS_ERROR;
605         }
606
607         ret = samdb_copy_template(module->ldb, msg2, "(&(CN=TemplateForeignSecurityPrincipal)(objectclass=foreignSecurityPrincipalTemplate))");
608         if (ret != 0) {
609                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "samldb_fill_foreignSecurityPrincipal_object: Error copying template!\n");
610                 talloc_free(mem_ctx);
611                 return ret;
612         }
613
614         rdn = ldb_dn_get_rdn(msg2, msg2->dn);
615
616         if (strcasecmp(rdn->name, "cn") != 0) {
617                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for ForeignSecurityPrincipal, should be CN=!", rdn->name);
618                 talloc_free(mem_ctx);
619                 return LDB_ERR_CONSTRAINT_VIOLATION;
620         }
621
622         /* Slightly different for the foreign sids.  We don't want
623          * domain SIDs ending up there, it would cause all sorts of
624          * pain */
625
626         sid = dom_sid_parse_talloc(msg2, (const char *)rdn->value.data);
627         if (!sid) {
628                 ldb_set_errstring(module->ldb, "No valid found SID in ForeignSecurityPrincipal CN!");
629                 talloc_free(mem_ctx);
630                 return LDB_ERR_CONSTRAINT_VIOLATION;
631         }
632
633         if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
634                 talloc_free(sid);
635                 return LDB_ERR_OPERATIONS_ERROR;
636         }
637
638         dom_sid = dom_sid_dup(mem_ctx, sid);
639         if (!dom_sid) {
640                 talloc_free(mem_ctx);
641                 return LDB_ERR_OPERATIONS_ERROR;
642         }
643         /* get the domain component part of the provided SID */
644         dom_sid->num_auths--;
645
646         /* find the domain DN */
647
648         ret = gendb_search(module->ldb,
649                            mem_ctx, NULL, &dom_msgs, dom_attrs,
650                            "(&(objectSid=%s)(objectclass=domain))",
651                            ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
652         if (ret >= 1) {
653                 /* We don't really like the idea of foreign sids that are not foreign, but it happens */
654                 const char *name = samdb_result_string(dom_msgs[0], "name", NULL);
655                 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", 
656                           dom_sid_string(mem_ctx, sid), name); 
657         } else if (ret == -1) {
658                 ldb_asprintf_errstring(module->ldb,
659                                         "samldb_fill_foreignSecurityPrincipal_object: error searching for a domain with this sid: %s\n", 
660                                         dom_sid_string(mem_ctx, dom_sid));
661                 talloc_free(dom_msgs);
662                 return LDB_ERR_OPERATIONS_ERROR;
663         }
664
665         /* This isn't an operation on a domain we know about, so just
666          * check for the SID, looking for duplicates via the common
667          * code */
668         ret = samldb_notice_sid(module, msg2, sid);
669         if (ret == 0) {
670                 talloc_steal(msg, msg2);
671                 *ret_msg = msg2;
672         }
673         
674         return ret;
675 }
676
677 /* add_record */
678
679 /*
680  * FIXME
681  *
682  * Actually this module is not async at all as it does a number of sync searches
683  * in the process. It still to be decided how to deal with it properly so it is
684  * left SYNC for now until we think of a good solution.
685  */
686
687 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
688 {
689         const struct ldb_message *msg = req->op.add.message;
690         struct ldb_message *msg2 = NULL;
691         struct ldb_request *down_req;
692         int ret;
693
694         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "samldb_add_record\n");
695
696         if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
697                 return ldb_next_request(module, req);
698         }
699
700         /* is user or computer? */
701         if ((samdb_find_attribute(module->ldb, msg, "objectclass", "user") != NULL) ||
702             (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL)) {
703                 /*  add all relevant missing objects */
704                 ret = samldb_fill_user_or_computer_object(module, msg, &msg2);
705                 if (ret) {
706                         return ret;
707                 }
708         }
709
710         /* is group? add all relevant missing objects */
711         if ( ! msg2 ) {
712                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "group") != NULL) {
713                         ret = samldb_fill_group_object(module, msg, &msg2);
714                         if (ret) {
715                                 return ret;
716                         }
717                 }
718         }
719
720         /* perhaps a foreignSecurityPrincipal? */
721         if ( ! msg2 ) {
722                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "foreignSecurityPrincipal") != NULL) {
723                         ret = samldb_fill_foreignSecurityPrincipal_object(module, msg, &msg2);
724                         if (ret) {
725                                 return ret;
726                         }
727                 }
728         }
729
730         if (msg2 == NULL) {
731                 return ldb_next_request(module, req);
732         }
733
734         down_req = talloc(module, struct ldb_request);
735         if (down_req == NULL) {
736                 return LDB_ERR_OPERATIONS_ERROR;
737         }
738
739         *down_req = *req;
740         
741         down_req->op.add.message = talloc_steal(down_req, msg2);
742
743         ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
744
745         /* go on with the call chain */
746         ret = ldb_next_request(module, down_req);
747
748         /* do not free down_req as the call results may be linked to it,
749          * it will be freed when the upper level request get freed */
750         if (ret == LDB_SUCCESS) {
751                 req->handle = down_req->handle;
752         }
753
754         return ret;
755 }
756
757 static int samldb_init(struct ldb_module *module)
758 {
759         return ldb_next_init(module);
760 }
761
762 static const struct ldb_module_ops samldb_ops = {
763         .name          = "samldb",
764         .init_context  = samldb_init,
765         .add           = samldb_add,
766 };
767
768
769 int samldb_module_init(void)
770 {
771         return ldb_register_module(&samldb_ops);
772 }