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