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