r26540: Revert my previous commit after concerns raised by Andrew.
[samba.git] / source4 / dsdb / samdb / ldb_modules / objectclass.c
1 /* 
2    ldb database library
3
4    Copyright (C) Simo Sorce  2006
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22  *  Name: ldb
23  *
24  *  Component: objectClass sorting module
25  *
26  *  Description: 
27  *  - sort the objectClass attribute into the class
28  *    hierarchy, 
29  *  - fix DNs and attributes into 'standard' case
30  *  - Add objectCategory and ntSecurityDescriptor defaults
31  *
32  *  Author: Andrew Bartlett
33  */
34
35
36 #include "includes.h"
37 #include "ldb/include/ldb.h"
38 #include "ldb/include/ldb_errors.h"
39 #include "ldb/include/ldb_private.h"
40 #include "dsdb/samdb/samdb.h"
41 #include "lib/util/dlinklist.h"
42 #include "librpc/ndr/libndr.h"
43 #include "librpc/gen_ndr/ndr_security.h"
44 #include "libcli/security/security.h"
45 #include "auth/auth.h"
46
47 struct oc_context {
48
49         enum oc_step {OC_DO_REQ, OC_SEARCH_SELF, OC_DO_MOD, 
50                       OC_SEARCH_ADD_PARENT, OC_DO_ADD, 
51                       OC_SEARCH_RENAME_PARENT, OC_DO_RENAME} step;
52
53         struct ldb_module *module;
54         struct ldb_request *orig_req;
55
56         struct ldb_request *down_req;
57
58         struct ldb_request *search_req;
59         struct ldb_reply *search_res;
60
61         struct ldb_request *add_req;
62         struct ldb_request *mod_req;
63         struct ldb_request *rename_req;
64 };
65
66 struct class_list {
67         struct class_list *prev, *next;
68         const struct dsdb_class *objectclass;
69 };
70
71 static int objectclass_do_add(struct ldb_handle *h);
72
73 static struct ldb_handle *oc_init_handle(struct ldb_request *req, struct ldb_module *module)
74 {
75         struct oc_context *ac;
76         struct ldb_handle *h;
77
78         h = talloc_zero(req, struct ldb_handle);
79         if (h == NULL) {
80                 ldb_set_errstring(module->ldb, "Out of Memory");
81                 return NULL;
82         }
83
84         h->module = module;
85
86         ac = talloc_zero(h, struct oc_context);
87         if (ac == NULL) {
88                 ldb_set_errstring(module->ldb, "Out of Memory");
89                 talloc_free(h);
90                 return NULL;
91         }
92
93         h->private_data = (void *)ac;
94
95         h->state = LDB_ASYNC_INIT;
96         h->status = LDB_SUCCESS;
97
98         ac->module = module;
99         ac->orig_req = req;
100
101         return h;
102 }
103
104 /* Sort objectClasses into correct order, and validate that all
105  * objectClasses specified actually exist in the schema
106  */
107
108 static int objectclass_sort(struct ldb_module *module,
109                             const struct dsdb_schema *schema,
110                             struct ldb_message *msg, /* so that when we create new elements, we put it on the right parent */
111                             TALLOC_CTX *mem_ctx,
112                             struct ldb_message_element *objectclass_element,
113                             struct class_list **sorted_out) 
114 {
115         int i;
116         int layer;
117         struct class_list *sorted = NULL, *parent_class = NULL,
118                 *subclass = NULL, *unsorted = NULL, *current, *poss_subclass, *poss_parent, *new_parent;
119         /* DESIGN:
120          *
121          * We work on 4 different 'bins' (implemented here as linked lists):
122          *
123          * * sorted:       the eventual list, in the order we wish to push
124          *                 into the database.  This is the only ordered list.
125          *
126          * * parent_class: The current parent class 'bin' we are
127          *                 trying to find subclasses for
128          *
129          * * subclass:     The subclasses we have found so far
130          *
131          * * unsorted:     The remaining objectClasses
132          *
133          * The process is a matter of filtering objectClasses up from
134          * unsorted into sorted.  Order is irrelevent in the later 3 'bins'.
135          * 
136          * We start with 'top' (found and promoted to parent_class
137          * initially).  Then we find (in unsorted) all the direct
138          * subclasses of 'top'.  parent_classes is concatenated onto
139          * the end of 'sorted', and subclass becomes the list in
140          * parent_class.
141          *
142          * We then repeat, until we find no more subclasses.  Any left
143          * over classes are added to the end.
144          *
145          */
146
147         /* Firstly, dump all the objectClass elements into the
148          * unsorted bin, except for 'top', which is special */
149         for (i=0; i < objectclass_element->num_values; i++) {
150                 current = talloc(mem_ctx, struct class_list);
151                 if (!current) {
152                         ldb_set_errstring(module->ldb, "objectclass: out of memory allocating objectclass list");
153                         talloc_free(mem_ctx);
154                         return LDB_ERR_OPERATIONS_ERROR;
155                 }
156                 current->objectclass = dsdb_class_by_lDAPDisplayName(schema, (const char *)objectclass_element->values[i].data);
157                 if (!current->objectclass) {
158                         ldb_asprintf_errstring(module->ldb, "objectclass %s is not a valid objectClass in schema", (const char *)objectclass_element->values[i].data);
159                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
160                 }
161
162                 /* this is the root of the tree.  We will start
163                  * looking for subclasses from here */
164                 if (ldb_attr_cmp("top", current->objectclass->lDAPDisplayName) == 0) {
165                         DLIST_ADD_END(parent_class, current, struct class_list *);
166                 } else {
167                         DLIST_ADD_END(unsorted, current, struct class_list *);
168                 }
169         }
170
171         if (parent_class == NULL) {
172                 current = talloc(mem_ctx, struct class_list);
173                 current->objectclass = dsdb_class_by_lDAPDisplayName(schema, "top");
174                 DLIST_ADD_END(parent_class, current, struct class_list *);
175         }
176
177         /* For each object:  find parent chain */
178         for (current = unsorted; schema && current; current = current->next) {
179                 for (poss_parent = unsorted; poss_parent; poss_parent = poss_parent->next) {
180                         if (ldb_attr_cmp(poss_parent->objectclass->lDAPDisplayName, current->objectclass->subClassOf) == 0) {
181                                 break;
182                         }
183                 }
184                 /* If we didn't get to the end of the list, we need to add this parent */
185                 if (poss_parent || (ldb_attr_cmp("top", current->objectclass->subClassOf) == 0)) {
186                         continue;
187                 }
188
189                 new_parent = talloc(mem_ctx, struct class_list);
190                 new_parent->objectclass = dsdb_class_by_lDAPDisplayName(schema, current->objectclass->subClassOf);
191                 DLIST_ADD_END(unsorted, new_parent, struct class_list *);
192         }
193
194         /* DEBUGGING aid:  how many layers are we down now? */
195         layer = 0;
196         do {
197                 layer++;
198                 /* Find all the subclasses of classes in the
199                  * parent_classes.  Push them onto the subclass list */
200
201                 /* Ensure we don't bother if there are no unsorted entries left */
202                 for (current = parent_class; schema && unsorted && current; current = current->next) {
203                         /* Walk the list of possible subclasses in unsorted */
204                         for (poss_subclass = unsorted; poss_subclass; ) {
205                                 struct class_list *next;
206                                 
207                                 /* Save the next pointer, as the DLIST_ macros will change poss_subclass->next */
208                                 next = poss_subclass->next;
209
210                                 if (ldb_attr_cmp(poss_subclass->objectclass->subClassOf, current->objectclass->lDAPDisplayName) == 0) {
211                                         DLIST_REMOVE(unsorted, poss_subclass);
212                                         DLIST_ADD(subclass, poss_subclass);
213                                         
214                                         break;
215                                 }
216                                 poss_subclass = next;
217                         }
218                 }
219
220                 /* Now push the parent_classes as sorted, we are done with
221                 these.  Add to the END of the list by concatenation */
222                 DLIST_CONCATENATE(sorted, parent_class, struct class_list *);
223
224                 /* and now find subclasses of these */
225                 parent_class = subclass;
226                 subclass = NULL;
227
228                 /* If we didn't find any subclasses we will fall out
229                  * the bottom here */
230         } while (parent_class);
231
232         if (!unsorted) {
233                 *sorted_out = sorted;
234                 return LDB_SUCCESS;
235         }
236
237         if (!schema) {
238                 /* If we don't have schema yet, then just merge the lists again */
239                 DLIST_CONCATENATE(sorted, unsorted, struct class_list *);
240                 *sorted_out = sorted;
241                 return LDB_SUCCESS;
242         }
243
244         /* This shouldn't happen, and would break MMC, perhaps there
245          * was no 'top', a conflict in the objectClasses or some other
246          * schema error?
247          */
248         ldb_asprintf_errstring(module->ldb, "objectclass %s is not a valid objectClass in objectClass chain", unsorted->objectclass->lDAPDisplayName);
249         return LDB_ERR_OBJECT_CLASS_VIOLATION;
250 }
251
252 static DATA_BLOB *get_sd(struct ldb_module *module, TALLOC_CTX *mem_ctx, 
253                          const struct dsdb_class *objectclass) 
254 {
255         enum ndr_err_code ndr_err;
256         DATA_BLOB *linear_sd;
257         struct auth_session_info *session_info
258                 = ldb_get_opaque(module->ldb, "sessionInfo");
259         struct security_descriptor *sd
260                 = sddl_decode(mem_ctx, 
261                               objectclass->defaultSecurityDescriptor,
262                               samdb_domain_sid(module->ldb));
263
264         if (!session_info || !session_info->security_token) {
265                 return NULL;
266         }
267         
268         sd->owner_sid = session_info->security_token->user_sid;
269         sd->group_sid = session_info->security_token->group_sid;
270         
271         linear_sd = talloc(mem_ctx, DATA_BLOB);
272         if (!linear_sd) {
273                 return NULL;
274         }
275
276         ndr_err = ndr_push_struct_blob(linear_sd, mem_ctx, sd,
277                                        (ndr_push_flags_fn_t)ndr_push_security_descriptor);
278         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
279                 return NULL;
280         }
281         
282         return linear_sd;
283
284 }
285
286 static int get_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
287 {
288         struct oc_context *ac;
289
290         ac = talloc_get_type(context, struct oc_context);
291
292         /* we are interested only in the single reply (base search) we receive here */
293         if (ares->type == LDB_REPLY_ENTRY) {
294                 if (ac->search_res != NULL) {
295                         ldb_set_errstring(ldb, "Too many results");
296                         talloc_free(ares);
297                         return LDB_ERR_OPERATIONS_ERROR;
298                 }
299
300                 ac->search_res = talloc_move(ac, &ares);
301         } else {
302                 talloc_free(ares);
303         }
304
305         return LDB_SUCCESS;
306 }
307
308 /* Fix up the DN to be in the standard form, taking particular care to match the parent DN
309
310    This should mean that if the parent is:
311     CN=Users,DC=samba,DC=example,DC=com
312    and a proposed child is
313     cn=Admins ,cn=USERS,dc=Samba,dc=example,dc=COM
314
315    The resulting DN should be:
316
317     CN=Admins,CN=Users,DC=samba,DC=example,DC=com
318    
319  */
320 static int fix_dn(TALLOC_CTX *mem_ctx, 
321                   struct ldb_dn *newdn, struct ldb_dn *parent_dn, 
322                   struct ldb_dn **fixed_dn) 
323 {
324         char *upper_rdn_attr;
325         /* Fix up the DN to be in the standard form, taking particular care to match the parent DN */
326         *fixed_dn = ldb_dn_copy(mem_ctx, parent_dn);
327
328         /* We need the attribute name in upper case */
329         upper_rdn_attr = strupper_talloc(*fixed_dn, 
330                                          ldb_dn_get_rdn_name(newdn));
331         if (!upper_rdn_attr) {
332                 return LDB_ERR_OPERATIONS_ERROR;
333         }
334                                                
335         /* Create a new child */
336         if (ldb_dn_add_child_fmt(*fixed_dn, "X=X") == false) {
337                 return LDB_ERR_OPERATIONS_ERROR;
338         }
339
340         /* And replace it with CN=foo (we need the attribute in upper case */
341         return ldb_dn_set_component(*fixed_dn, 0, upper_rdn_attr,
342                                     *ldb_dn_get_rdn_val(newdn));
343 }
344
345 /* Fix all attribute names to be in the correct case, and check they are all valid per the schema */
346 static int fix_attributes(struct ldb_context *ldb, const struct dsdb_schema *schema, struct ldb_message *msg) 
347 {
348         int i;
349         for (i=0; i < msg->num_elements; i++) {
350                 const struct dsdb_attribute *attribute = dsdb_attribute_by_lDAPDisplayName(schema, msg->elements[i].name);
351                 if (!attribute) {
352                         ldb_asprintf_errstring(ldb, "attribute %s is not a valid attribute in schema", msg->elements[i].name);
353                         return LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE;
354                 }
355                 msg->elements[i].name = attribute->lDAPDisplayName;
356         }
357
358         return LDB_SUCCESS;
359 }
360
361 static int objectclass_add(struct ldb_module *module, struct ldb_request *req)
362 {
363
364         static const char * const attrs[] = { NULL };
365
366         struct ldb_handle *h;
367         struct oc_context *ac;
368         struct ldb_dn *parent_dn;
369         int ret;
370         
371         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectclass_add\n");
372
373         /* do not manipulate our control entries */
374         if (ldb_dn_is_special(req->op.add.message->dn)) {
375                 return ldb_next_request(module, req);
376         }
377
378         /* Need to object to this, but cn=rootdse doesn't hae an objectClass... */
379         if (ldb_msg_find_element(req->op.add.message, 
380                                  "objectClass") == NULL) {
381                 return ldb_next_request(module, req);
382         }
383
384         h = oc_init_handle(req, module);
385         if (!h) {
386                 return LDB_ERR_OPERATIONS_ERROR;
387         }
388         ac = talloc_get_type(h->private_data, struct oc_context);
389         
390         /* return or own handle to deal with this call */
391         req->handle = h;
392
393         /* If there isn't a parent, just go on to the add processing */
394         if (ldb_dn_get_comp_num(ac->orig_req->op.add.message->dn) == 1) {
395                 return objectclass_do_add(h);
396         }
397
398         parent_dn = ldb_dn_get_parent(ac, ac->orig_req->op.add.message->dn);
399         if (parent_dn == NULL) {
400                 ldb_oom(module->ldb);
401                 return LDB_ERR_OPERATIONS_ERROR;
402         }
403
404         ret = ldb_build_search_req(&ac->search_req, module->ldb,
405                                    ac, parent_dn, LDB_SCOPE_BASE,
406                                    "(objectClass=*)",
407                                    attrs, NULL, 
408                                    ac, get_search_callback);
409         if (ret != LDB_SUCCESS) {
410                 return ret;
411         }
412
413         talloc_steal(ac->search_req, parent_dn);
414
415         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
416
417         ac->step = OC_SEARCH_ADD_PARENT;
418
419         return ldb_next_request(ac->module, ac->search_req);
420 }
421
422 static int objectclass_do_add(struct ldb_handle *h) 
423 {
424         const struct dsdb_schema *schema;
425         struct oc_context *ac;
426         struct ldb_message_element *objectclass_element;
427         struct ldb_message *msg;
428         TALLOC_CTX *mem_ctx;
429         struct class_list *sorted, *current;
430         int ret;
431       
432         ac = talloc_get_type(h->private_data, struct oc_context);
433         schema = dsdb_get_schema(ac->module->ldb);
434
435         mem_ctx = talloc_new(ac);
436         if (mem_ctx == NULL) {
437                 return LDB_ERR_OPERATIONS_ERROR;
438         }
439
440         ac->add_req = talloc(ac, struct ldb_request);
441         if (ac->add_req == NULL) {
442                 talloc_free(mem_ctx);
443                 return LDB_ERR_OPERATIONS_ERROR;
444         }
445
446         *ac->add_req = *ac->orig_req;
447
448         ac->add_req->op.add.message = msg = ldb_msg_copy_shallow(ac->add_req, ac->orig_req->op.add.message);
449
450         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->add_req);
451         
452         /* Check we have a valid parent */
453         if (ac->search_res == NULL) {
454                 if (ldb_dn_compare(ldb_get_root_basedn(ac->module->ldb), ac->orig_req->op.add.message->dn) == 0) {
455                         /* Allow the tree to be started */
456                         
457                         /* but don't keep any error string, it's meaningless */
458                         ldb_set_errstring(ac->module->ldb, NULL);
459                 } else {
460                         ldb_asprintf_errstring(ac->module->ldb, "objectclass: Cannot add %s, parent does not exist!", 
461                                                ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
462                         return LDB_ERR_UNWILLING_TO_PERFORM;
463                 }
464         } else {
465                 
466                 /* Fix up the DN to be in the standard form, taking particular care to match the parent DN */
467                 ret = fix_dn(msg, 
468                              ac->orig_req->op.add.message->dn,
469                              ac->search_res->message->dn,
470                              &msg->dn);
471
472                 if (ret != LDB_SUCCESS) {
473                         ldb_asprintf_errstring(ac->module->ldb, "Could not munge DN %s into normal form", 
474                                                ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
475                         return ret;
476                 }
477
478                 /* TODO: Check this is a valid child to this parent,
479                  * by reading the allowedChildClasses and
480                  * allowedChildClasssesEffective attributes */
481
482         }
483
484         if (schema) {
485                 ret = fix_attributes(ac->module->ldb, schema, msg);
486                 if (ret != LDB_SUCCESS) {
487                         talloc_free(mem_ctx);
488                         return ret;
489                 }
490
491                 /* This is now the objectClass list from the database */
492                 objectclass_element = ldb_msg_find_element(msg, "objectClass");
493                 
494                 if (!objectclass_element) {
495                         /* Where did it go?  bail now... */
496                         talloc_free(mem_ctx);
497                         return LDB_ERR_OPERATIONS_ERROR;
498                 }
499                 ret = objectclass_sort(ac->module, schema, msg, mem_ctx, objectclass_element, &sorted);
500                 if (ret != LDB_SUCCESS) {
501                         talloc_free(mem_ctx);
502                         return ret;
503                 }
504                 
505                 ldb_msg_remove_attr(msg, "objectClass");
506                 ret = ldb_msg_add_empty(msg, "objectClass", 0, NULL);
507                 
508                 if (ret != LDB_SUCCESS) {
509                         talloc_free(mem_ctx);
510                         return ret;
511                 }
512                 
513                 /* We must completely replace the existing objectClass entry,
514                  * because we need it sorted */
515                 
516                 /* Move from the linked list back into an ldb msg */
517                 for (current = sorted; current; current = current->next) {
518                         ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
519                         if (ret != LDB_SUCCESS) {
520                                 ldb_set_errstring(ac->module->ldb, 
521                                                   "objectclass: could not re-add sorted "
522                                                   "objectclass to modify msg");
523                                 talloc_free(mem_ctx);
524                                 return ret;
525                         }
526                         /* Last one is the critical one */
527                         if (!current->next) {
528                                 if (!ldb_msg_find_element(msg, "objectCategory")) {
529                                         ldb_msg_add_string(msg, "objectCategory", 
530                                                            current->objectclass->defaultObjectCategory);
531                                 }
532                                 if (!ldb_msg_find_element(msg, "nTSecurityDescriptor")) {
533                                         DATA_BLOB *sd = get_sd(ac->module, mem_ctx, current->objectclass);
534                                         ldb_msg_add_steal_value(msg, "nTSecurityDescriptor", sd);
535                                 }
536                         }
537                 }
538         }
539
540         talloc_free(mem_ctx);
541         ret = ldb_msg_sanity_check(ac->module->ldb, msg);
542
543
544         if (ret != LDB_SUCCESS) {
545                 return ret;
546         }
547
548         h->state = LDB_ASYNC_INIT;
549         h->status = LDB_SUCCESS;
550
551         ac->step = OC_DO_ADD;
552
553         /* perform the add */
554         return ldb_next_request(ac->module, ac->add_req);
555 }
556
557 static int objectclass_modify(struct ldb_module *module, struct ldb_request *req)
558 {
559         struct ldb_message_element *objectclass_element;
560         struct ldb_message *msg;
561         const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
562         int ret;
563
564         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectclass_modify\n");
565
566         /* do not manipulate our control entries */
567         if (ldb_dn_is_special(req->op.mod.message->dn)) {
568                 return ldb_next_request(module, req);
569         }
570         
571         /* Without schema, there isn't much to do here */
572         if (!schema) {
573                 return ldb_next_request(module, req);
574         }
575         objectclass_element = ldb_msg_find_element(req->op.mod.message, "objectClass");
576
577         /* If no part of this touches the objectClass, then we don't
578          * need to make any changes.  */
579
580         /* If the only operation is the deletion of the objectClass
581          * then go on with just fixing the attribute case */
582         if (!objectclass_element) {
583                 struct ldb_request *down_req = talloc(req, struct ldb_request);
584                 if (down_req == NULL) {
585                         ldb_set_errstring(module->ldb, "Out of memory!");
586                         return LDB_ERR_OPERATIONS_ERROR;
587                 }
588                 
589                 *down_req = *req; /* copy the request */
590                 
591                 down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
592                 
593                 if (down_req->op.mod.message == NULL) {
594                         return LDB_ERR_OPERATIONS_ERROR;
595                 }
596                 
597                 ret = fix_attributes(module->ldb, schema, msg);
598                 if (ret != LDB_SUCCESS) {
599                         return ret;
600                 }
601
602                 /* go on with the call chain */
603                 ret = ldb_next_request(module, down_req);
604                 
605                 /* do not free down_req as the call results may be linked to it,
606                  * it will be freed when the upper level request get freed */
607                 if (ret == LDB_SUCCESS) {
608                         req->handle = down_req->handle;
609                 }
610                 return ret;
611         }
612
613         switch (objectclass_element->flags & LDB_FLAG_MOD_MASK) {
614         case LDB_FLAG_MOD_DELETE:
615                 if (objectclass_element->num_values == 0) {
616                         return LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED;
617                 }
618                 break;
619         case LDB_FLAG_MOD_REPLACE:
620         {
621                 struct ldb_request *down_req;
622                 struct class_list *sorted, *current;
623                 TALLOC_CTX *mem_ctx;
624                 mem_ctx = talloc_new(req);
625                 if (mem_ctx == NULL) {
626                         return LDB_ERR_OPERATIONS_ERROR;
627                 }
628
629                 /* prepare the first operation */
630                 down_req = talloc(req, struct ldb_request);
631                 if (down_req == NULL) {
632                         ldb_set_errstring(module->ldb, "Out of memory!");
633                         talloc_free(mem_ctx);
634                         return LDB_ERR_OPERATIONS_ERROR;
635                 }
636                 
637                 *down_req = *req; /* copy the request */
638                 
639                 down_req->op.mod.message = msg = ldb_msg_copy_shallow(down_req, req->op.mod.message);
640                 
641                 if (down_req->op.mod.message == NULL) {
642                         talloc_free(mem_ctx);
643                         return LDB_ERR_OPERATIONS_ERROR;
644                 }
645                 
646                 ret = fix_attributes(module->ldb, schema, msg);
647                 if (ret != LDB_SUCCESS) {
648                         talloc_free(mem_ctx);
649                         return ret;
650                 }
651
652                 ret = objectclass_sort(module, schema, msg, mem_ctx, objectclass_element, &sorted);
653                 if (ret != LDB_SUCCESS) {
654                         return ret;
655                 }
656
657                 /* We must completely replace the existing objectClass entry,
658                  * because we need it sorted */
659                 
660                 ldb_msg_remove_attr(msg, "objectClass");
661                 ret = ldb_msg_add_empty(msg, "objectClass", LDB_FLAG_MOD_REPLACE, NULL);
662                 
663                 if (ret != LDB_SUCCESS) {
664                         talloc_free(mem_ctx);
665                         return ret;
666                 }
667
668                 /* Move from the linked list back into an ldb msg */
669                 for (current = sorted; current; current = current->next) {
670                         ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
671                         if (ret != LDB_SUCCESS) {
672                                 ldb_set_errstring(module->ldb, "objectclass: could not re-add sorted objectclass to modify msg");
673                                 talloc_free(mem_ctx);
674                                 return ret;
675                         }
676                 }
677                 
678                 talloc_free(mem_ctx);
679
680                 ret = ldb_msg_sanity_check(module->ldb, msg);
681                 if (ret != LDB_SUCCESS) {
682                         talloc_free(mem_ctx);
683                         return ret;
684                 }
685                 
686                 /* go on with the call chain */
687                 ret = ldb_next_request(module, down_req);
688                 
689                 /* do not free down_req as the call results may be linked to it,
690                  * it will be freed when the upper level request get freed */
691                 if (ret == LDB_SUCCESS) {
692                         req->handle = down_req->handle;
693                 }
694                 return ret;
695         }
696         }
697
698         /* This isn't the default branch of the switch, but a 'in any
699          * other case'.  When a delete isn't for all objectClasses for
700          * example
701          */
702         {
703                 struct ldb_handle *h;
704                 struct oc_context *ac;
705                 
706                 h = oc_init_handle(req, module);
707                 if (!h) {
708                         return LDB_ERR_OPERATIONS_ERROR;
709                 }
710                 ac = talloc_get_type(h->private_data, struct oc_context);
711                 
712                 /* return or own handle to deal with this call */
713                 req->handle = h;
714                 
715                 /* prepare the first operation */
716                 ac->down_req = talloc(ac, struct ldb_request);
717                 if (ac->down_req == NULL) {
718                         ldb_oom(ac->module->ldb);
719                         return LDB_ERR_OPERATIONS_ERROR;
720                 }
721                 
722                 *(ac->down_req) = *req; /* copy the request */
723                 
724                 ac->down_req->op.mod.message = msg = ldb_msg_copy_shallow(ac->down_req, req->op.mod.message);
725                 
726                 if (ac->down_req->op.mod.message == NULL) {
727                         ldb_oom(ac->module->ldb);
728                         return LDB_ERR_OPERATIONS_ERROR;
729                 }
730                 
731                 ret = fix_attributes(ac->module->ldb, schema, msg);
732                 if (ret != LDB_SUCCESS) {
733                         ldb_oom(ac->module->ldb);
734                         return ret;
735                 }
736
737                 ac->down_req->context = NULL;
738                 ac->down_req->callback = NULL;
739                 ldb_set_timeout_from_prev_req(module->ldb, req, ac->down_req);
740                 
741                 ac->step = OC_DO_REQ;
742
743                 return ldb_next_request(module, ac->down_req);
744         }
745 }
746
747 static int objectclass_search_self(struct ldb_handle *h) 
748 {
749         int ret;
750         struct oc_context *ac;
751         static const char * const attrs[] = { "objectClass", NULL };
752
753         ac = talloc_get_type(h->private_data, struct oc_context);
754
755         ret = ldb_build_search_req(&ac->search_req, ac->module->ldb,
756                                    ac, ac->orig_req->op.mod.message->dn, LDB_SCOPE_BASE,
757                                    "(objectClass=*)",
758                                    attrs, NULL, 
759                                    ac, get_search_callback);
760
761         if (ret != LDB_SUCCESS) {
762                 return ret;
763         }
764
765         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
766
767         ac->step = OC_SEARCH_SELF;
768
769         return ldb_next_request(ac->module, ac->search_req);
770 }
771
772 static int objectclass_do_mod(struct ldb_handle *h) {
773
774         const struct dsdb_schema *schema;
775         struct oc_context *ac;
776         struct ldb_message_element *objectclass_element;
777         struct ldb_message *msg;
778         TALLOC_CTX *mem_ctx;
779         struct class_list *sorted, *current;
780         int ret;
781       
782         ac = talloc_get_type(h->private_data, struct oc_context);
783         schema = dsdb_get_schema(ac->module->ldb);
784
785         mem_ctx = talloc_new(ac);
786         if (mem_ctx == NULL) {
787                 return LDB_ERR_OPERATIONS_ERROR;
788         }
789
790         ac->mod_req = talloc(ac, struct ldb_request);
791         if (ac->mod_req == NULL) {
792                 talloc_free(mem_ctx);
793                 return LDB_ERR_OPERATIONS_ERROR;
794         }
795
796         ac->mod_req->operation = LDB_MODIFY;
797         ac->mod_req->controls = NULL;
798         ac->mod_req->context = ac;
799         ac->mod_req->callback = NULL;
800         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->mod_req);
801         
802         /* use a new message structure */
803         ac->mod_req->op.mod.message = msg = ldb_msg_new(ac->mod_req);
804         if (msg == NULL) {
805                 ldb_set_errstring(ac->module->ldb, "objectclass: could not create new modify msg");
806                 talloc_free(mem_ctx);
807                 return LDB_ERR_OPERATIONS_ERROR;
808         }
809
810         /* This is now the objectClass list from the database */
811         objectclass_element = ldb_msg_find_element(ac->search_res->message, 
812                                                    "objectClass");
813         if (!objectclass_element) {
814                 /* Where did it go?  bail now... */
815                 talloc_free(mem_ctx);
816                 return LDB_ERR_OPERATIONS_ERROR;
817         }
818         
819         /* modify dn */
820         msg->dn = ac->orig_req->op.mod.message->dn;
821
822         ret = objectclass_sort(ac->module, schema, msg, mem_ctx, objectclass_element, &sorted);
823         if (ret != LDB_SUCCESS) {
824                 return ret;
825         }
826
827         /* We must completely replace the existing objectClass entry.
828          * We could do a constrained add/del, but we are meant to be
829          * in a transaction... */
830
831         ret = ldb_msg_add_empty(msg, "objectClass", LDB_FLAG_MOD_REPLACE, NULL);
832         if (ret != LDB_SUCCESS) {
833                 ldb_set_errstring(ac->module->ldb, "objectclass: could not clear objectclass in modify msg");
834                 talloc_free(mem_ctx);
835                 return ret;
836         }
837         
838         /* Move from the linked list back into an ldb msg */
839         for (current = sorted; current; current = current->next) {
840                 ret = ldb_msg_add_string(msg, "objectClass", current->objectclass->lDAPDisplayName);
841                 if (ret != LDB_SUCCESS) {
842                         ldb_set_errstring(ac->module->ldb, "objectclass: could not re-add sorted objectclass to modify msg");
843                         talloc_free(mem_ctx);
844                         return ret;
845                 }
846         }
847
848         ret = ldb_msg_sanity_check(ac->module->ldb, msg);
849         if (ret != LDB_SUCCESS) {
850                 talloc_free(mem_ctx);
851                 return ret;
852         }
853
854
855         h->state = LDB_ASYNC_INIT;
856         h->status = LDB_SUCCESS;
857
858         ac->step = OC_DO_MOD;
859
860         talloc_free(mem_ctx);
861         /* perform the search */
862         return ldb_next_request(ac->module, ac->mod_req);
863 }
864
865 static int objectclass_rename(struct ldb_module *module, struct ldb_request *req)
866 {
867
868         static const char * const attrs[] = { NULL };
869
870         struct ldb_handle *h;
871         struct oc_context *ac;
872         struct ldb_dn *parent_dn;
873         int ret;
874         
875         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "objectclass_rename\n");
876
877         if (ldb_dn_is_special(req->op.rename.newdn)) { /* do not manipulate our control entries */
878                 return ldb_next_request(module, req);
879         }
880         
881         /* Firstly ensure we are not trying to rename it to be a child of itself */
882         if ((ldb_dn_compare_base(req->op.rename.olddn, req->op.rename.newdn) == 0) 
883             && (ldb_dn_compare(req->op.rename.olddn, req->op.rename.newdn) != 0)) {
884                 ldb_asprintf_errstring(module->ldb, "Cannot rename %s to be a child of itself",
885                                        ldb_dn_get_linearized(req->op.rename.olddn));
886                 return LDB_ERR_UNWILLING_TO_PERFORM;
887         }
888
889         h = oc_init_handle(req, module);
890         if (!h) {
891                 return LDB_ERR_OPERATIONS_ERROR;
892         }
893         ac = talloc_get_type(h->private_data, struct oc_context);
894         
895         /* return or own handle to deal with this call */
896         req->handle = h;
897
898         parent_dn = ldb_dn_get_parent(ac, ac->orig_req->op.rename.newdn);
899         if (parent_dn == NULL) {
900                 ldb_oom(module->ldb);
901                 return LDB_ERR_OPERATIONS_ERROR;
902         }
903         ret = ldb_build_search_req(&ac->search_req, module->ldb,
904                                    ac, parent_dn, LDB_SCOPE_BASE,
905                                    "(objectClass=*)",
906                                    attrs, NULL, 
907                                    ac, get_search_callback);
908         if (ret != LDB_SUCCESS) {
909                 return ret;
910         }
911         talloc_steal(ac->search_req, parent_dn);
912         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->search_req);
913
914         ac->step = OC_SEARCH_RENAME_PARENT;
915
916         return ldb_next_request(ac->module, ac->search_req);
917 }
918
919 static int objectclass_do_rename(struct ldb_handle *h) 
920 {
921         struct oc_context *ac;
922         int ret;
923       
924         ac = talloc_get_type(h->private_data, struct oc_context);
925
926         ac->rename_req = talloc(ac, struct ldb_request);
927         if (ac->rename_req == NULL) {
928                 return LDB_ERR_OPERATIONS_ERROR;
929         }
930
931         *ac->rename_req = *ac->orig_req;
932
933         ldb_set_timeout_from_prev_req(ac->module->ldb, ac->orig_req, ac->rename_req);
934         
935         /* Check we have a valid parent */
936         if (ac->search_res == NULL) {
937                 ldb_asprintf_errstring(ac->module->ldb, "objectclass: Cannot rename %s, parent does not exist!", 
938                                        ldb_dn_get_linearized(ac->orig_req->op.rename.newdn));
939                 return LDB_ERR_UNWILLING_TO_PERFORM;
940         }
941         
942         /* Fix up the DN to be in the standard form, taking particular care to match the parent DN */
943         ret = fix_dn(ac->rename_req, 
944                      ac->orig_req->op.rename.newdn, 
945                      ac->search_res->message->dn, 
946                      &ac->rename_req->op.rename.newdn);
947
948         if (ret != LDB_SUCCESS) {
949                 return ret;
950         }
951
952         /* TODO: Check this is a valid child to this parent,
953          * by reading the allowedChildClasses and
954          * allowedChildClasssesEffective attributes */
955
956         h->state = LDB_ASYNC_INIT;
957         h->status = LDB_SUCCESS;
958
959         ac->step = OC_DO_RENAME;
960
961         /* perform the rename */
962         return ldb_next_request(ac->module, ac->rename_req);
963 }
964
965 static int oc_wait(struct ldb_handle *handle) {
966         struct oc_context *ac;
967         int ret;
968     
969         if (!handle || !handle->private_data) {
970                 return LDB_ERR_OPERATIONS_ERROR;
971         }
972
973         if (handle->state == LDB_ASYNC_DONE) {
974                 return handle->status;
975         }
976
977         handle->state = LDB_ASYNC_PENDING;
978         handle->status = LDB_SUCCESS;
979
980         ac = talloc_get_type(handle->private_data, struct oc_context);
981
982         switch (ac->step) {
983         case OC_DO_REQ:
984                 ret = ldb_wait(ac->down_req->handle, LDB_WAIT_NONE);
985
986                 if (ret != LDB_SUCCESS) {
987                         handle->status = ret;
988                         goto done;
989                 }
990                 if (ac->down_req->handle->status != LDB_SUCCESS) {
991                         handle->status = ac->down_req->handle->status;
992                         goto done;
993                 }
994
995                 if (ac->down_req->handle->state != LDB_ASYNC_DONE) {
996                         return LDB_SUCCESS;
997                 }
998
999                 /* mods done, go on */
1000                 return objectclass_search_self(handle);
1001
1002         case OC_SEARCH_SELF:
1003                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1004
1005                 if (ret != LDB_SUCCESS) {
1006                         handle->status = ret;
1007                         goto done;
1008                 }
1009                 if (ac->search_req->handle->status != LDB_SUCCESS) {
1010                         handle->status = ac->search_req->handle->status;
1011                         goto done;
1012                 }
1013
1014                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1015                         return LDB_SUCCESS;
1016                 }
1017
1018                 /* self search done, go on */
1019                 return objectclass_do_mod(handle);
1020
1021         case OC_DO_MOD:
1022                 ret = ldb_wait(ac->mod_req->handle, LDB_WAIT_NONE);
1023
1024                 if (ret != LDB_SUCCESS) {
1025                         handle->status = ret;
1026                         goto done;
1027                 }
1028                 if (ac->mod_req->handle->status != LDB_SUCCESS) {
1029                         handle->status = ac->mod_req->handle->status;
1030                         goto done;
1031                 }
1032
1033                 if (ac->mod_req->handle->state != LDB_ASYNC_DONE) {
1034                         return LDB_SUCCESS;
1035                 }
1036
1037                 break;
1038                 
1039         case OC_SEARCH_ADD_PARENT:
1040                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1041
1042                 if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
1043                         handle->status = ret;
1044                         goto done;
1045                 }
1046                 if (ac->search_req->handle->status != LDB_SUCCESS
1047                     && ac->search_req->handle->status != LDB_ERR_NO_SUCH_OBJECT) {
1048                         handle->status = ac->search_req->handle->status;
1049                         goto done;
1050                 }
1051
1052                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1053                         return LDB_SUCCESS;
1054                 }
1055
1056                 /* parent search done, go on */
1057                 return objectclass_do_add(handle);
1058
1059         case OC_DO_ADD:
1060                 ret = ldb_wait(ac->add_req->handle, LDB_WAIT_NONE);
1061
1062                 if (ret != LDB_SUCCESS) {
1063                         handle->status = ret;
1064                         goto done;
1065                 }
1066                 if (ac->add_req->handle->status != LDB_SUCCESS) {
1067                         handle->status = ac->add_req->handle->status;
1068                         goto done;
1069                 }
1070
1071                 if (ac->add_req->handle->state != LDB_ASYNC_DONE) {
1072                         return LDB_SUCCESS;
1073                 }
1074
1075                 break;
1076                 
1077         case OC_SEARCH_RENAME_PARENT:
1078                 ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
1079
1080                 if (ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
1081                         handle->status = ret;
1082                         goto done;
1083                 }
1084                 if (ac->search_req->handle->status != LDB_SUCCESS && ac->search_req->handle->status != LDB_ERR_NO_SUCH_OBJECT) {
1085                         handle->status = ac->search_req->handle->status;
1086                         goto done;
1087                 }
1088
1089                 if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
1090                         return LDB_SUCCESS;
1091                 }
1092
1093                 /* parent search done, go on */
1094                 return objectclass_do_rename(handle);
1095
1096         case OC_DO_RENAME:
1097                 ret = ldb_wait(ac->rename_req->handle, LDB_WAIT_NONE);
1098
1099                 if (ret != LDB_SUCCESS) {
1100                         handle->status = ret;
1101                         goto done;
1102                 }
1103                 if (ac->rename_req->handle->status != LDB_SUCCESS) {
1104                         handle->status = ac->rename_req->handle->status;
1105                         goto done;
1106                 }
1107
1108                 if (ac->rename_req->handle->state != LDB_ASYNC_DONE) {
1109                         return LDB_SUCCESS;
1110                 }
1111
1112                 break;
1113                 
1114         default:
1115                 ret = LDB_ERR_OPERATIONS_ERROR;
1116                 goto done;
1117         }
1118
1119         ret = LDB_SUCCESS;
1120
1121 done:
1122         handle->state = LDB_ASYNC_DONE;
1123         return ret;
1124 }
1125
1126 static int oc_wait_all(struct ldb_handle *handle) {
1127
1128         int ret;
1129
1130         while (handle->state != LDB_ASYNC_DONE) {
1131                 ret = oc_wait(handle);
1132                 if (ret != LDB_SUCCESS) {
1133                         return ret;
1134                 }
1135         }
1136
1137         return handle->status;
1138 }
1139
1140 static int objectclass_wait(struct ldb_handle *handle, enum ldb_wait_type type)
1141 {
1142         if (type == LDB_WAIT_ALL) {
1143                 return oc_wait_all(handle);
1144         } else {
1145                 return oc_wait(handle);
1146         }
1147 }
1148
1149 static const struct ldb_module_ops objectclass_ops = {
1150         .name              = "objectclass",
1151         .add           = objectclass_add,
1152         .modify        = objectclass_modify,
1153         .rename        = objectclass_rename,
1154         .wait          = objectclass_wait
1155 };
1156
1157 int ldb_objectclass_init(void)
1158 {
1159         return ldb_register_module(&objectclass_ops);
1160 }
1161