b316686fd032f3af75c26406917163a48460f6c6
[npower/samba.git] / source4 / dsdb / schema / schema_set.c
1 /*
2    Unix SMB/CIFS implementation.
3    DSDB schema header
4
5    Copyright (C) Stefan Metzmacher <metze@samba.org> 2006-2007
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006-2008
7    Copyright (C) Matthieu Patou <mat@matws.net> 2011
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22 */
23
24 #include "includes.h"
25 #include "lib/util/dlinklist.h"
26 #include "dsdb/samdb/samdb.h"
27 #include <ldb_module.h>
28 #include "param/param.h"
29 #include "librpc/ndr/libndr.h"
30 #include "librpc/gen_ndr/ndr_misc.h"
31 #include "lib/util/tsort.h"
32
33 /* change this when we change something in our schema code that
34  * requires a re-index of the database
35  */
36 #define SAMDB_INDEXING_VERSION "3"
37
38 /*
39   override the name to attribute handler function
40  */
41 const struct ldb_schema_attribute *dsdb_attribute_handler_override(struct ldb_context *ldb,
42                                                                    void *private_data,
43                                                                    const char *name)
44 {
45         struct dsdb_schema *schema = talloc_get_type_abort(private_data, struct dsdb_schema);
46         const struct dsdb_attribute *a = dsdb_attribute_by_lDAPDisplayName(schema, name);
47         if (a == NULL) {
48                 /* this will fall back to ldb internal handling */
49                 return NULL;
50         }
51         return a->ldb_schema_attribute;
52 }
53
54 /*
55  * Set the attribute handlers onto the LDB, and potentially write the
56  * @INDEXLIST, @IDXONE and @ATTRIBUTES records.  The @ATTRIBUTES records
57  * are required so we can operate on a schema-less database (say the
58  * backend during emergency fixes) and during the schema load.
59  */
60 int dsdb_schema_set_indices_and_attributes(struct ldb_context *ldb,
61                                            struct dsdb_schema *schema,
62                                            enum schema_set_enum mode)
63 {
64         int ret = LDB_SUCCESS;
65         struct ldb_result *res;
66         struct ldb_result *res_idx;
67         struct dsdb_attribute *attr;
68         struct ldb_message *mod_msg;
69         TALLOC_CTX *mem_ctx;
70         struct ldb_message *msg;
71         struct ldb_message *msg_idx;
72
73         struct loadparm_context *lp_ctx =
74                 talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
75                                 struct loadparm_context);
76         bool guid_indexing = true;
77         bool declare_ordered_integer_in_attributes = true;
78         uint32_t pack_format_override;
79         if (lp_ctx != NULL) {
80                 /*
81                  * GUID indexing is wanted by Samba by default.  This allows
82                  * an override in a specific case for downgrades.
83                  */
84                 guid_indexing = lpcfg_parm_bool(lp_ctx,
85                                                 NULL,
86                                                 "dsdb",
87                                                 "guid index",
88                                                 true);
89                 /*
90                  * If the pack format has been overridden to a previous
91                  * version, then act like ORDERED_INTEGER doesn't exist,
92                  * because it's a new type and we don't want to deal with
93                  * possible issues with databases containing version 1 pack
94                  * format and ordered types.
95                  *
96                  * This approach means that the @ATTRIBUTES will be
97                  * incorrect for integers.  Many other @ATTRIBUTES
98                  * values are gross simplifications, but the presence
99                  * of the ORDERED_INTEGER keyword prevents the old
100                  * Samba from starting and then forcing a reindex.
101                  *
102                  * It is too difficult to override the actual index
103                  * formatter, but this doesn't matter in practice.
104                  */
105                 pack_format_override =
106                         (intptr_t)ldb_get_opaque(ldb, "pack_format_override");
107                 if (pack_format_override == LDB_PACKING_FORMAT ||
108                     pack_format_override == LDB_PACKING_FORMAT_NODN) {
109                         declare_ordered_integer_in_attributes = false;
110                 }
111         }
112         /* setup our own attribute name to schema handler */
113         ldb_schema_attribute_set_override_handler(ldb, dsdb_attribute_handler_override, schema);
114         ldb_schema_set_override_indexlist(ldb, true);
115         if (guid_indexing) {
116                 ldb_schema_set_override_GUID_index(ldb, "objectGUID", "GUID");
117         }
118
119         if (mode == SCHEMA_MEMORY_ONLY) {
120                 return ret;
121         }
122
123         mem_ctx = talloc_new(ldb);
124         if (!mem_ctx) {
125                 return ldb_oom(ldb);
126         }
127
128         msg = ldb_msg_new(mem_ctx);
129         if (!msg) {
130                 ldb_oom(ldb);
131                 goto op_error;
132         }
133         msg_idx = ldb_msg_new(mem_ctx);
134         if (!msg_idx) {
135                 ldb_oom(ldb);
136                 goto op_error;
137         }
138         msg->dn = ldb_dn_new(msg, ldb, "@ATTRIBUTES");
139         if (!msg->dn) {
140                 ldb_oom(ldb);
141                 goto op_error;
142         }
143         msg_idx->dn = ldb_dn_new(msg_idx, ldb, "@INDEXLIST");
144         if (!msg_idx->dn) {
145                 ldb_oom(ldb);
146                 goto op_error;
147         }
148
149         ret = ldb_msg_add_string(msg_idx, "@IDXONE", "1");
150         if (ret != LDB_SUCCESS) {
151                 goto op_error;
152         }
153
154         if (guid_indexing) {
155                 ret = ldb_msg_add_string(msg_idx, "@IDXGUID", "objectGUID");
156                 if (ret != LDB_SUCCESS) {
157                         goto op_error;
158                 }
159
160                 ret = ldb_msg_add_string(msg_idx, "@IDX_DN_GUID", "GUID");
161                 if (ret != LDB_SUCCESS) {
162                         goto op_error;
163                 }
164         }
165
166         ret = ldb_msg_add_string(msg_idx, "@SAMDB_INDEXING_VERSION", SAMDB_INDEXING_VERSION);
167         if (ret != LDB_SUCCESS) {
168                 goto op_error;
169         }
170
171         ret = ldb_msg_add_string(msg_idx, SAMBA_FEATURES_SUPPORTED_FLAG, "1");
172         if (ret != LDB_SUCCESS) {
173                 goto op_error;
174         }
175
176         for (attr = schema->attributes; attr; attr = attr->next) {
177                 const char *syntax = attr->syntax->ldb_syntax;
178
179                 if (!syntax) {
180                         syntax = attr->syntax->ldap_oid;
181                 }
182
183                 /*
184                  * Write out a rough approximation of the schema
185                  * as an @ATTRIBUTES value, for bootstrapping.
186                  * Only write ORDERED_INTEGER if we're using GUID indexes,
187                  */
188                 if (strcmp(syntax, LDB_SYNTAX_INTEGER) == 0) {
189                         ret = ldb_msg_add_string(msg, attr->lDAPDisplayName, "INTEGER");
190                 } else if (strcmp(syntax, LDB_SYNTAX_ORDERED_INTEGER) == 0) {
191                         if (declare_ordered_integer_in_attributes &&
192                             guid_indexing) {
193                                 /*
194                                  * The normal production case
195                                  */
196                                 ret = ldb_msg_add_string(msg,
197                                                          attr->lDAPDisplayName,
198                                                          "ORDERED_INTEGER");
199                         } else {
200                                 /*
201                                  * For this mode, we are going back to
202                                  * before GUID indexing so we write it out
203                                  * as INTEGER
204                                  *
205                                  * Down in LDB, the special handler
206                                  * (index_format_fn) that made
207                                  * ORDERED_INTEGER and INTEGER
208                                  * different has been disabled.
209                                  */
210                                 ret = ldb_msg_add_string(msg,
211                                                          attr->lDAPDisplayName,
212                                                          "INTEGER");
213                         }
214                 } else if (strcmp(syntax, LDB_SYNTAX_DIRECTORY_STRING) == 0) {
215                         ret = ldb_msg_add_string(msg, attr->lDAPDisplayName,
216                                                  "CASE_INSENSITIVE");
217                 }
218                 if (ret != LDB_SUCCESS) {
219                         break;
220                 }
221
222                 if (attr->searchFlags & SEARCH_FLAG_ATTINDEX) {
223                         /*
224                          * When preparing to downgrade Samba, we need to write
225                          * out an LDB without the new key word ORDERED_INTEGER.
226                          */
227                         if (strcmp(syntax, LDB_SYNTAX_ORDERED_INTEGER) == 0
228                             && !declare_ordered_integer_in_attributes) {
229                                 /*
230                                  * Ugly, but do nothing, the best
231                                  * thing is to omit the reference
232                                  * entirely, the next transaction will
233                                  * spot this and rewrite everything.
234                                  *
235                                  * This way nothing will look at the
236                                  * index for this attribute until
237                                  * Samba starts and this is all
238                                  * rewritten.
239                                  */
240                         } else {
241                                 ret = ldb_msg_add_string(msg_idx, "@IDXATTR", attr->lDAPDisplayName);
242                                 if (ret != LDB_SUCCESS) {
243                                         break;
244                                 }
245                         }
246                 }
247         }
248
249         if (ret != LDB_SUCCESS) {
250                 talloc_free(mem_ctx);
251                 return ret;
252         }
253
254         /*
255          * Try to avoid churning the attributes too much,
256          * we only want to do this if they have changed
257          */
258         ret = ldb_search(ldb, mem_ctx, &res, msg->dn, LDB_SCOPE_BASE, NULL,
259                          NULL);
260         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
261                 if (mode == SCHEMA_COMPARE) {
262                         /* We are probably not in a transaction */
263                         goto wrong_mode;
264                 }
265                 ret = ldb_add(ldb, msg);
266         } else if (ret != LDB_SUCCESS) {
267         } else if (res->count != 1) {
268                 if (mode == SCHEMA_COMPARE) {
269                         /* We are probably not in a transaction */
270                         goto wrong_mode;
271                 }
272                 ret = ldb_add(ldb, msg);
273         } else {
274                 /* Annoyingly added to our search results */
275                 ldb_msg_remove_attr(res->msgs[0], "distinguishedName");
276
277                 ret = ldb_msg_difference(ldb, mem_ctx,
278                                          res->msgs[0], msg, &mod_msg);
279                 if (ret != LDB_SUCCESS) {
280                         goto op_error;
281                 }
282                 if (mod_msg->num_elements > 0) {
283                         /*
284                          * Do the replace with the difference, as we
285                          * are under the read lock and we wish to do a
286                          * delete of any removed/renamed attributes
287                          */
288                         if (mode == SCHEMA_COMPARE) {
289                                 /* We are probably not in a transaction */
290                                 goto wrong_mode;
291                         }
292                         ret = dsdb_modify(ldb, mod_msg, 0);
293                 }
294                 talloc_free(mod_msg);
295         }
296
297         if (ret == LDB_ERR_OPERATIONS_ERROR || ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS || ret == LDB_ERR_INVALID_DN_SYNTAX) {
298                 /* We might be on a read-only DB or LDAP */
299                 ret = LDB_SUCCESS;
300         }
301         if (ret != LDB_SUCCESS) {
302                 DBG_ERR("Failed to set schema into @ATTRIBUTES: %s\n",
303                         ldb_errstring(ldb));
304                 talloc_free(mem_ctx);
305                 return ret;
306         }
307
308         /* Now write out the indexes, as found in the schema (if they have changed) */
309
310         ret = ldb_search(ldb, mem_ctx, &res_idx, msg_idx->dn, LDB_SCOPE_BASE,
311                          NULL, NULL);
312         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
313                 if (mode == SCHEMA_COMPARE) {
314                         /* We are probably not in a transaction */
315                         goto wrong_mode;
316                 }
317                 ret = ldb_add(ldb, msg_idx);
318         } else if (ret != LDB_SUCCESS) {
319         } else if (res_idx->count != 1) {
320                 if (mode == SCHEMA_COMPARE) {
321                         /* We are probably not in a transaction */
322                         goto wrong_mode;
323                 }
324                 ret = ldb_add(ldb, msg_idx);
325         } else {
326                 /* Annoyingly added to our search results */
327                 ldb_msg_remove_attr(res_idx->msgs[0], "distinguishedName");
328
329                 ret = ldb_msg_difference(ldb, mem_ctx,
330                                          res_idx->msgs[0], msg_idx, &mod_msg);
331                 if (ret != LDB_SUCCESS) {
332                         goto op_error;
333                 }
334
335                 /*
336                  * We don't want to re-index just because we didn't
337                  * see this flag
338                  *
339                  * DO NOT backport this logic earlier than 4.7, it
340                  * isn't needed and would be dangerous before 4.6,
341                  * where we add logic to samba_dsdb to manage
342                  * @SAMBA_FEATURES_SUPPORTED and need to know if the
343                  * DB has been re-opened by an earlier version.
344                  *
345                  */
346
347                 if (mod_msg->num_elements == 1
348                     && ldb_attr_cmp(mod_msg->elements[0].name,
349                                     SAMBA_FEATURES_SUPPORTED_FLAG) == 0) {
350                         /*
351                          * Ignore only adding
352                          * @SAMBA_FEATURES_SUPPORTED
353                          */
354                 } else if (mod_msg->num_elements > 0) {
355
356                         /*
357                          * Do the replace with the difference, as we
358                          * are under the read lock and we wish to do a
359                          * delete of any removed/renamed attributes
360                          */
361                         if (mode == SCHEMA_COMPARE) {
362                                 /* We are probably not in a transaction */
363                                 goto wrong_mode;
364                         }
365                         ret = dsdb_modify(ldb, mod_msg, 0);
366                 }
367                 talloc_free(mod_msg);
368         }
369         if (ret == LDB_ERR_OPERATIONS_ERROR || ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS || ret == LDB_ERR_INVALID_DN_SYNTAX) {
370                 /* We might be on a read-only DB */
371                 ret = LDB_SUCCESS;
372         }
373
374         if (ret != LDB_SUCCESS) {
375                 DBG_ERR("Failed to set schema into @INDEXLIST: %s\n",
376                         ldb_errstring(ldb));
377         }
378
379         talloc_free(mem_ctx);
380         return ret;
381
382 op_error:
383         talloc_free(mem_ctx);
384         return ldb_operr(ldb);
385
386 wrong_mode:
387         talloc_free(mem_ctx);
388         return LDB_ERR_BUSY;
389 }
390
391
392 /*
393   create extra attribute shortcuts
394  */
395 static void dsdb_setup_attribute_shortcuts(struct ldb_context *ldb, struct dsdb_schema *schema)
396 {
397         struct dsdb_attribute *attribute;
398
399         /* setup fast access to one_way_link and DN format */
400         for (attribute=schema->attributes; attribute; attribute=attribute->next) {
401                 attribute->dn_format = dsdb_dn_oid_to_format(attribute->syntax->ldap_oid);
402
403                 if (attribute->dn_format == DSDB_INVALID_DN) {
404                         attribute->one_way_link = false;
405                         continue;
406                 }
407
408                 /* these are not considered to be one way links for
409                    the purpose of DN link fixups */
410                 if (ldb_attr_cmp("distinguishedName", attribute->lDAPDisplayName) == 0 ||
411                     ldb_attr_cmp("objectCategory", attribute->lDAPDisplayName) == 0) {
412                         attribute->one_way_link = false;
413                         continue;
414                 }
415
416                 if (attribute->linkID == 0) {
417                         attribute->one_way_link = true;
418                         continue;
419                 }
420                 /* handle attributes with a linkID but no backlink */
421                 if ((attribute->linkID & 1) == 0 &&
422                     dsdb_attribute_by_linkID(schema, attribute->linkID + 1) == NULL) {
423                         attribute->one_way_link = true;
424                         continue;
425                 }
426                 attribute->one_way_link = false;
427         }
428 }
429
430 static int uint32_cmp(uint32_t c1, uint32_t c2)
431 {
432         if (c1 == c2) return 0;
433         return c1 > c2 ? 1 : -1;
434 }
435
436 static int dsdb_compare_class_by_lDAPDisplayName(struct dsdb_class **c1, struct dsdb_class **c2)
437 {
438         return strcasecmp((*c1)->lDAPDisplayName, (*c2)->lDAPDisplayName);
439 }
440 static int dsdb_compare_class_by_governsID_id(struct dsdb_class **c1, struct dsdb_class **c2)
441 {
442         return uint32_cmp((*c1)->governsID_id, (*c2)->governsID_id);
443 }
444 static int dsdb_compare_class_by_governsID_oid(struct dsdb_class **c1, struct dsdb_class **c2)
445 {
446         return strcasecmp((*c1)->governsID_oid, (*c2)->governsID_oid);
447 }
448 static int dsdb_compare_class_by_cn(struct dsdb_class **c1, struct dsdb_class **c2)
449 {
450         return strcasecmp((*c1)->cn, (*c2)->cn);
451 }
452
453 static int dsdb_compare_attribute_by_lDAPDisplayName(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
454 {
455         return strcasecmp((*a1)->lDAPDisplayName, (*a2)->lDAPDisplayName);
456 }
457 static int dsdb_compare_attribute_by_attributeID_id(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
458 {
459         return uint32_cmp((*a1)->attributeID_id, (*a2)->attributeID_id);
460 }
461 static int dsdb_compare_attribute_by_msDS_IntId(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
462 {
463         return uint32_cmp((*a1)->msDS_IntId, (*a2)->msDS_IntId);
464 }
465 static int dsdb_compare_attribute_by_attributeID_oid(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
466 {
467         return strcasecmp((*a1)->attributeID_oid, (*a2)->attributeID_oid);
468 }
469 static int dsdb_compare_attribute_by_linkID(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
470 {
471         return uint32_cmp((*a1)->linkID, (*a2)->linkID);
472 }
473
474 /**
475  * Clean up Classes and Attributes accessor arrays
476  */
477 static void dsdb_sorted_accessors_free(struct dsdb_schema *schema)
478 {
479         /* free classes accessors */
480         TALLOC_FREE(schema->classes_by_lDAPDisplayName);
481         TALLOC_FREE(schema->classes_by_governsID_id);
482         TALLOC_FREE(schema->classes_by_governsID_oid);
483         TALLOC_FREE(schema->classes_by_cn);
484         /* free attribute accessors */
485         TALLOC_FREE(schema->attributes_by_lDAPDisplayName);
486         TALLOC_FREE(schema->attributes_by_attributeID_id);
487         TALLOC_FREE(schema->attributes_by_msDS_IntId);
488         TALLOC_FREE(schema->attributes_by_attributeID_oid);
489         TALLOC_FREE(schema->attributes_by_linkID);
490 }
491
492 /*
493   create the sorted accessor arrays for the schema
494  */
495 int dsdb_setup_sorted_accessors(struct ldb_context *ldb,
496                                 struct dsdb_schema *schema)
497 {
498         struct dsdb_class *cur;
499         struct dsdb_attribute *a;
500         unsigned int i;
501         unsigned int num_int_id;
502         int ret;
503
504         for (i=0; i < schema->classes_to_remove_size; i++) {
505                 DLIST_REMOVE(schema->classes, schema->classes_to_remove[i]);
506                 TALLOC_FREE(schema->classes_to_remove[i]);
507         }
508         for (i=0; i < schema->attributes_to_remove_size; i++) {
509                 DLIST_REMOVE(schema->attributes, schema->attributes_to_remove[i]);
510                 TALLOC_FREE(schema->attributes_to_remove[i]);
511         }
512
513         TALLOC_FREE(schema->classes_to_remove);
514         schema->classes_to_remove_size = 0;
515         TALLOC_FREE(schema->attributes_to_remove);
516         schema->attributes_to_remove_size = 0;
517
518         /* free all caches */
519         dsdb_sorted_accessors_free(schema);
520
521         /* count the classes */
522         for (i=0, cur=schema->classes; cur; i++, cur=cur->next) /* noop */ ;
523         schema->num_classes = i;
524
525         /* setup classes_by_* */
526         schema->classes_by_lDAPDisplayName = talloc_array(schema, struct dsdb_class *, i);
527         schema->classes_by_governsID_id    = talloc_array(schema, struct dsdb_class *, i);
528         schema->classes_by_governsID_oid   = talloc_array(schema, struct dsdb_class *, i);
529         schema->classes_by_cn              = talloc_array(schema, struct dsdb_class *, i);
530         if (schema->classes_by_lDAPDisplayName == NULL ||
531             schema->classes_by_governsID_id == NULL ||
532             schema->classes_by_governsID_oid == NULL ||
533             schema->classes_by_cn == NULL) {
534                 goto failed;
535         }
536
537         for (i=0, cur=schema->classes; cur; i++, cur=cur->next) {
538                 schema->classes_by_lDAPDisplayName[i] = cur;
539                 schema->classes_by_governsID_id[i]    = cur;
540                 schema->classes_by_governsID_oid[i]   = cur;
541                 schema->classes_by_cn[i]              = cur;
542         }
543
544         /* sort the arrays */
545         TYPESAFE_QSORT(schema->classes_by_lDAPDisplayName, schema->num_classes, dsdb_compare_class_by_lDAPDisplayName);
546         TYPESAFE_QSORT(schema->classes_by_governsID_id, schema->num_classes, dsdb_compare_class_by_governsID_id);
547         TYPESAFE_QSORT(schema->classes_by_governsID_oid, schema->num_classes, dsdb_compare_class_by_governsID_oid);
548         TYPESAFE_QSORT(schema->classes_by_cn, schema->num_classes, dsdb_compare_class_by_cn);
549
550         /* now build the attribute accessor arrays */
551
552         /* count the attributes
553          * and attributes with msDS-IntId set */
554         num_int_id = 0;
555         for (i=0, a=schema->attributes; a; i++, a=a->next) {
556                 if (a->msDS_IntId != 0) {
557                         num_int_id++;
558                 }
559         }
560         schema->num_attributes = i;
561         schema->num_int_id_attr = num_int_id;
562
563         /* setup attributes_by_* */
564         schema->attributes_by_lDAPDisplayName = talloc_array(schema, struct dsdb_attribute *, i);
565         schema->attributes_by_attributeID_id    = talloc_array(schema, struct dsdb_attribute *, i);
566         schema->attributes_by_msDS_IntId        = talloc_array(schema,
567                                                                struct dsdb_attribute *, num_int_id);
568         schema->attributes_by_attributeID_oid   = talloc_array(schema, struct dsdb_attribute *, i);
569         schema->attributes_by_linkID              = talloc_array(schema, struct dsdb_attribute *, i);
570         if (schema->attributes_by_lDAPDisplayName == NULL ||
571             schema->attributes_by_attributeID_id == NULL ||
572             schema->attributes_by_msDS_IntId == NULL ||
573             schema->attributes_by_attributeID_oid == NULL ||
574             schema->attributes_by_linkID == NULL) {
575                 goto failed;
576         }
577
578         num_int_id = 0;
579         for (i=0, a=schema->attributes; a; i++, a=a->next) {
580                 schema->attributes_by_lDAPDisplayName[i] = a;
581                 schema->attributes_by_attributeID_id[i]    = a;
582                 schema->attributes_by_attributeID_oid[i]   = a;
583                 schema->attributes_by_linkID[i]          = a;
584                 /* append attr-by-msDS-IntId values */
585                 if (a->msDS_IntId != 0) {
586                         schema->attributes_by_msDS_IntId[num_int_id] = a;
587                         num_int_id++;
588                 }
589         }
590         SMB_ASSERT(num_int_id == schema->num_int_id_attr);
591
592         /* sort the arrays */
593         TYPESAFE_QSORT(schema->attributes_by_lDAPDisplayName, schema->num_attributes, dsdb_compare_attribute_by_lDAPDisplayName);
594         TYPESAFE_QSORT(schema->attributes_by_attributeID_id, schema->num_attributes, dsdb_compare_attribute_by_attributeID_id);
595         TYPESAFE_QSORT(schema->attributes_by_msDS_IntId, schema->num_int_id_attr, dsdb_compare_attribute_by_msDS_IntId);
596         TYPESAFE_QSORT(schema->attributes_by_attributeID_oid, schema->num_attributes, dsdb_compare_attribute_by_attributeID_oid);
597         TYPESAFE_QSORT(schema->attributes_by_linkID, schema->num_attributes, dsdb_compare_attribute_by_linkID);
598
599         dsdb_setup_attribute_shortcuts(ldb, schema);
600
601         ret = schema_fill_constructed(schema);
602         if (ret != LDB_SUCCESS) {
603                 dsdb_sorted_accessors_free(schema);
604                 return ret;
605         }
606
607         return LDB_SUCCESS;
608
609 failed:
610         dsdb_sorted_accessors_free(schema);
611         return ldb_oom(ldb);
612 }
613
614 /**
615  * Attach the schema to an opaque pointer on the ldb,
616  * so ldb modules can find it
617  */
618 int dsdb_set_schema_refresh_function(struct ldb_context *ldb,
619                                      dsdb_schema_refresh_fn refresh_fn,
620                                      struct ldb_module *module)
621 {
622         int ret = ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", refresh_fn);
623         if (ret != LDB_SUCCESS) {
624                 return ret;
625         }
626
627         ret = ldb_set_opaque(ldb, "dsdb_schema_refresh_fn_private_data", module);
628         if (ret != LDB_SUCCESS) {
629                 return ret;
630         }
631         return LDB_SUCCESS;
632 }
633
634 /**
635  * Attach the schema to an opaque pointer on the ldb,
636  * so ldb modules can find it
637  */
638 int dsdb_set_schema(struct ldb_context *ldb,
639                     struct dsdb_schema *schema,
640                     enum schema_set_enum write_indices_and_attributes)
641 {
642         struct dsdb_schema *old_schema;
643         int ret;
644
645         ret = dsdb_setup_sorted_accessors(ldb, schema);
646         if (ret != LDB_SUCCESS) {
647                 return ret;
648         }
649
650         old_schema = ldb_get_opaque(ldb, "dsdb_schema");
651
652         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", NULL);
653         if (ret != LDB_SUCCESS) {
654                 return ret;
655         }
656
657         ret = ldb_set_opaque(ldb, "dsdb_schema", schema);
658         if (ret != LDB_SUCCESS) {
659                 return ret;
660         }
661
662         talloc_steal(ldb, schema);
663
664         /* Set the new attributes based on the new schema */
665         ret = dsdb_schema_set_indices_and_attributes(ldb, schema,
666                                                      write_indices_and_attributes);
667         if (ret != LDB_SUCCESS) {
668                 return ret;
669         }
670
671         /*
672          * Remove the reference to the schema we just overwrote - if there was
673          * none, NULL is harmless here.
674          */
675         if (old_schema != schema) {
676                 talloc_unlink(ldb, old_schema);
677         }
678
679         return ret;
680 }
681
682 /**
683  * Global variable to hold one copy of the schema, used to avoid memory bloat
684  */
685 static struct dsdb_schema *global_schema;
686
687 /**
688  * Make this ldb use a specified schema, already fully calculated and belonging to another ldb
689  *
690  * The write_indices_and_attributes controls writing of the @ records
691  * because we cannot write to a database that does not yet exist on
692  * disk.
693  */
694 int dsdb_reference_schema(struct ldb_context *ldb, struct dsdb_schema *schema,
695                           enum schema_set_enum write_indices_and_attributes)
696 {
697         int ret;
698         struct dsdb_schema *old_schema;
699         old_schema = ldb_get_opaque(ldb, "dsdb_schema");
700         ret = ldb_set_opaque(ldb, "dsdb_schema", schema);
701         if (ret != LDB_SUCCESS) {
702                 return ret;
703         }
704
705         /* Remove the reference to the schema we just overwrote - if there was
706          * none, NULL is harmless here */
707         talloc_unlink(ldb, old_schema);
708
709         if (talloc_reference(ldb, schema) == NULL) {
710                 return ldb_oom(ldb);
711         }
712
713         /* Make this ldb use local schema preferably */
714         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", NULL);
715         if (ret != LDB_SUCCESS) {
716                 return ret;
717         }
718
719         ret = ldb_set_opaque(ldb, "dsdb_refresh_fn", NULL);
720         if (ret != LDB_SUCCESS) {
721                 return ret;
722         }
723
724         ret = ldb_set_opaque(ldb, "dsdb_refresh_fn_private_data", NULL);
725         if (ret != LDB_SUCCESS) {
726                 return ret;
727         }
728
729         ret = dsdb_schema_set_indices_and_attributes(ldb, schema, write_indices_and_attributes);
730         if (ret != LDB_SUCCESS) {
731                 return ret;
732         }
733
734         return LDB_SUCCESS;
735 }
736
737 /**
738  * Make this ldb use the 'global' schema, setup to avoid having multiple copies in this process
739  */
740 int dsdb_set_global_schema(struct ldb_context *ldb)
741 {
742         int ret;
743         void *use_global_schema = (void *)1;
744         struct dsdb_schema *old_schema = ldb_get_opaque(ldb, "dsdb_schema");
745
746         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", use_global_schema);
747         if (ret != LDB_SUCCESS) {
748                 return ret;
749         }
750
751         if (global_schema == NULL) {
752                 return LDB_SUCCESS;
753         }
754
755         /* Remove any pointer to a previous schema */
756         ret = ldb_set_opaque(ldb, "dsdb_schema", NULL);
757         if (ret != LDB_SUCCESS) {
758                 return ret;
759         }
760
761         /* Remove the reference to the schema we just overwrote - if there was
762          * none, NULL is harmless here */
763         talloc_unlink(ldb, old_schema);
764
765         /* Set the new attributes based on the new schema */
766         /* Don't write indices and attributes, it's expensive */
767         ret = dsdb_schema_set_indices_and_attributes(ldb, global_schema, SCHEMA_MEMORY_ONLY);
768         if (ret == LDB_SUCCESS) {
769                 /* Keep a reference to this schema, just in case the original copy is replaced */
770                 if (talloc_reference(ldb, global_schema) == NULL) {
771                         return ldb_oom(ldb);
772                 }
773         }
774
775         return ret;
776 }
777
778 bool dsdb_uses_global_schema(struct ldb_context *ldb)
779 {
780         return (ldb_get_opaque(ldb, "dsdb_use_global_schema") != NULL);
781 }
782
783 /**
784  * Find the schema object for this ldb
785  *
786  * If reference_ctx is not NULL, then talloc_reference onto that context
787  */
788
789 struct dsdb_schema *dsdb_get_schema(struct ldb_context *ldb, TALLOC_CTX *reference_ctx)
790 {
791         const void *p;
792         struct dsdb_schema *schema_out = NULL;
793         struct dsdb_schema *schema_in = NULL;
794         dsdb_schema_refresh_fn refresh_fn;
795         struct ldb_module *loaded_from_module;
796         bool use_global_schema;
797         TALLOC_CTX *tmp_ctx = talloc_new(reference_ctx);
798         if (tmp_ctx == NULL) {
799                 return NULL;
800         }
801
802         /* see if we have a cached copy */
803         use_global_schema = dsdb_uses_global_schema(ldb);
804         if (use_global_schema) {
805                 schema_in = global_schema;
806         } else {
807                 p = ldb_get_opaque(ldb, "dsdb_schema");
808                 if (p != NULL) {
809                         schema_in = talloc_get_type_abort(p, struct dsdb_schema);
810                 }
811         }
812
813         refresh_fn = ldb_get_opaque(ldb, "dsdb_schema_refresh_fn");
814         if (refresh_fn) {
815                 loaded_from_module = ldb_get_opaque(ldb, "dsdb_schema_refresh_fn_private_data");
816
817                 SMB_ASSERT(loaded_from_module && (ldb_module_get_ctx(loaded_from_module) == ldb));
818         }
819
820         if (refresh_fn) {
821                 /* We need to guard against recursive calls here */
822                 if (ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", NULL) != LDB_SUCCESS) {
823                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
824                                       "dsdb_get_schema: clearing dsdb_schema_refresh_fn failed");
825                 } else {
826                         schema_out = refresh_fn(loaded_from_module,
827                                                 ldb_get_event_context(ldb),
828                                                 schema_in,
829                                                 use_global_schema);
830                 }
831                 if (ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", refresh_fn) != LDB_SUCCESS) {
832                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
833                                       "dsdb_get_schema: re-setting dsdb_schema_refresh_fn failed");
834                 }
835                 if (!schema_out) {
836                         schema_out = schema_in;
837                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
838                                       "dsdb_get_schema: refresh_fn() failed");
839                 }
840         } else {
841                 schema_out = schema_in;
842         }
843
844         /* This removes the extra reference above */
845         talloc_free(tmp_ctx);
846         if (!reference_ctx) {
847                 return schema_out;
848         } else {
849                 return talloc_reference(reference_ctx, schema_out);
850         }
851 }
852
853 /**
854  * Make the schema found on this ldb the 'global' schema
855  */
856
857 void dsdb_make_schema_global(struct ldb_context *ldb, struct dsdb_schema *schema)
858 {
859         if (!schema) {
860                 return;
861         }
862
863         if (global_schema) {
864                 talloc_unlink(NULL, global_schema);
865         }
866
867         /* we want the schema to be around permanently */
868         talloc_reparent(ldb, NULL, schema);
869         global_schema = schema;
870
871         /* This calls the talloc_reference() of the global schema back onto the ldb */
872         dsdb_set_global_schema(ldb);
873 }
874
875 /**
876  * When loading the schema from LDIF files, we don't get the extended DNs.
877  *
878  * We need to set these up, so that from the moment we start the provision,
879  * the defaultObjectCategory links are set up correctly.
880  */
881 int dsdb_schema_fill_extended_dn(struct ldb_context *ldb, struct dsdb_schema *schema)
882 {
883         struct dsdb_class *cur;
884         const struct dsdb_class *target_class;
885         for (cur = schema->classes; cur; cur = cur->next) {
886                 const struct ldb_val *rdn;
887                 struct ldb_val guid;
888                 NTSTATUS status;
889                 struct ldb_dn *dn = ldb_dn_new(NULL, ldb, cur->defaultObjectCategory);
890
891                 if (!dn) {
892                         return LDB_ERR_INVALID_DN_SYNTAX;
893                 }
894                 rdn = ldb_dn_get_component_val(dn, 0);
895                 if (!rdn) {
896                         talloc_free(dn);
897                         return LDB_ERR_INVALID_DN_SYNTAX;
898                 }
899                 target_class = dsdb_class_by_cn_ldb_val(schema, rdn);
900                 if (!target_class) {
901                         talloc_free(dn);
902                         return LDB_ERR_CONSTRAINT_VIOLATION;
903                 }
904
905                 status = GUID_to_ndr_blob(&target_class->objectGUID, dn, &guid);
906                 if (!NT_STATUS_IS_OK(status)) {
907                         talloc_free(dn);
908                         return ldb_operr(ldb);
909                 }
910                 ldb_dn_set_extended_component(dn, "GUID", &guid);
911
912                 cur->defaultObjectCategory = ldb_dn_get_extended_linearized(cur, dn, 1);
913                 talloc_free(dn);
914         }
915         return LDB_SUCCESS;
916 }
917
918 /**
919  * @brief Add a new element to the schema and checks if it's a duplicate
920  *
921  * This function will add a new element to the schema and checks for existing
922  * duplicates.
923  *
924  * @param[in]  ldb                A pointer to an LDB context
925  *
926  * @param[in]  schema             A pointer to the dsdb_schema where the element
927  *                                will be added.
928  *
929  * @param[in]  msg                The ldb_message object representing the element
930  *                                to add.
931  *
932  * @param[in]  checkdups          A boolean to indicate if checks for duplicates
933  *                                should be done.
934  *
935  * @return                        A WERROR code
936  */
937 WERROR dsdb_schema_set_el_from_ldb_msg_dups(struct ldb_context *ldb, struct dsdb_schema *schema,
938                                             struct ldb_message *msg, bool checkdups)
939 {
940         const char* tstring;
941         time_t ts;
942         tstring = ldb_msg_find_attr_as_string(msg, "whenChanged", NULL);
943         /* keep a trace of the ts of the most recently changed object */
944         if (tstring) {
945                 ts = ldb_string_to_time(tstring);
946                 if (ts > schema->ts_last_change) {
947                         schema->ts_last_change = ts;
948                 }
949         }
950         if (samdb_find_attribute(ldb, msg,
951                                  "objectclass", "attributeSchema") != NULL) {
952
953                 return dsdb_set_attribute_from_ldb_dups(ldb, schema, msg, checkdups);
954         } else if (samdb_find_attribute(ldb, msg,
955                                  "objectclass", "classSchema") != NULL) {
956                 return dsdb_set_class_from_ldb_dups(schema, msg, checkdups);
957         }
958         /* Don't fail on things not classes or attributes */
959         return WERR_OK;
960 }
961
962 WERROR dsdb_schema_set_el_from_ldb_msg(struct ldb_context *ldb,
963                                        struct dsdb_schema *schema,
964                                        struct ldb_message *msg)
965 {
966         return dsdb_schema_set_el_from_ldb_msg_dups(ldb, schema, msg, false);
967 }
968
969 /**
970  * Rather than read a schema from the LDB itself, read it from an ldif
971  * file.  This allows schema to be loaded and used while adding the
972  * schema itself to the directory.
973  *
974  * Should be called with a transaction (or failing that, have no concurrent
975  * access while called).
976  */
977
978 WERROR dsdb_set_schema_from_ldif(struct ldb_context *ldb,
979                                  const char *pf, const char *df,
980                                  const char *dn)
981 {
982         struct ldb_ldif *ldif;
983         struct ldb_message *msg;
984         TALLOC_CTX *mem_ctx;
985         WERROR status;
986         int ret;
987         struct dsdb_schema *schema;
988         const struct ldb_val *prefix_val;
989         const struct ldb_val *info_val;
990         struct ldb_val info_val_default;
991
992
993         mem_ctx = talloc_new(ldb);
994         if (!mem_ctx) {
995                 goto nomem;
996         }
997
998         schema = dsdb_new_schema(mem_ctx);
999         if (!schema) {
1000                 goto nomem;
1001         }
1002         schema->fsmo.we_are_master = true;
1003         schema->fsmo.update_allowed = true;
1004         schema->fsmo.master_dn = ldb_dn_new(schema, ldb, "@PROVISION_SCHEMA_MASTER");
1005         if (!schema->fsmo.master_dn) {
1006                 goto nomem;
1007         }
1008
1009         /*
1010          * load the prefixMap attribute from pf
1011          */
1012         ldif = ldb_ldif_read_string(ldb, &pf);
1013         if (!ldif) {
1014                 status = WERR_INVALID_PARAMETER;
1015                 goto failed;
1016         }
1017         talloc_steal(mem_ctx, ldif);
1018
1019         ret = ldb_msg_normalize(ldb, mem_ctx, ldif->msg, &msg);
1020         if (ret != LDB_SUCCESS) {
1021                 goto nomem;
1022         }
1023         talloc_free(ldif);
1024
1025         prefix_val = ldb_msg_find_ldb_val(msg, "prefixMap");
1026         if (!prefix_val) {
1027                 status = WERR_INVALID_PARAMETER;
1028                 goto failed;
1029         }
1030
1031         info_val = ldb_msg_find_ldb_val(msg, "schemaInfo");
1032         if (!info_val) {
1033                 status = dsdb_schema_info_blob_new(mem_ctx, &info_val_default);
1034                 W_ERROR_NOT_OK_GOTO(status, failed);
1035                 info_val = &info_val_default;
1036         }
1037
1038         status = dsdb_load_oid_mappings_ldb(schema, prefix_val, info_val);
1039         if (!W_ERROR_IS_OK(status)) {
1040                 DEBUG(0,("ERROR: dsdb_load_oid_mappings_ldb() failed with %s\n", win_errstr(status)));
1041                 goto failed;
1042         }
1043
1044         schema->ts_last_change = 0;
1045         /* load the attribute and class definitions out of df */
1046         while ((ldif = ldb_ldif_read_string(ldb, &df))) {
1047                 talloc_steal(mem_ctx, ldif);
1048
1049                 ret = ldb_msg_normalize(ldb, ldif, ldif->msg, &msg);
1050                 if (ret != LDB_SUCCESS) {
1051                         goto nomem;
1052                 }
1053
1054                 status = dsdb_schema_set_el_from_ldb_msg(ldb, schema, msg);
1055                 talloc_free(ldif);
1056                 if (!W_ERROR_IS_OK(status)) {
1057                         goto failed;
1058                 }
1059         }
1060
1061         /*
1062          * TODO We may need a transaction here, otherwise this causes races.
1063          *
1064          * To do so may require an ldb_in_transaction function. In the
1065          * meantime, assume that this is always called with a transaction or in
1066          * isolation.
1067          */
1068         ret = dsdb_set_schema(ldb, schema, SCHEMA_WRITE);
1069         if (ret != LDB_SUCCESS) {
1070                 status = WERR_FOOBAR;
1071                 DEBUG(0,("ERROR: dsdb_set_schema() failed with %s / %s\n",
1072                          ldb_strerror(ret), ldb_errstring(ldb)));
1073                 goto failed;
1074         }
1075
1076         ret = dsdb_schema_fill_extended_dn(ldb, schema);
1077         if (ret != LDB_SUCCESS) {
1078                 status = WERR_FOOBAR;
1079                 goto failed;
1080         }
1081
1082         goto done;
1083
1084 nomem:
1085         status = WERR_NOT_ENOUGH_MEMORY;
1086 failed:
1087 done:
1088         talloc_free(mem_ctx);
1089         return status;
1090 }