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