dsdb: disable ORDERED_INTEGER with MDB pack format v1
[metze/samba/wip.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                 ret = LDB_SUCCESS;
275                 /* Annoyingly added to our search results */
276                 ldb_msg_remove_attr(res->msgs[0], "distinguishedName");
277
278                 ret = ldb_msg_difference(ldb, mem_ctx,
279                                          res->msgs[0], msg, &mod_msg);
280                 if (ret != LDB_SUCCESS) {
281                         goto op_error;
282                 }
283                 if (mod_msg->num_elements > 0) {
284                         /*
285                          * Do the replace with the difference, as we
286                          * are under the read lock and we wish to do a
287                          * delete of any removed/renamed attributes
288                          */
289                         if (mode == SCHEMA_COMPARE) {
290                                 /* We are probably not in a transaction */
291                                 goto wrong_mode;
292                         }
293                         ret = dsdb_modify(ldb, mod_msg, 0);
294                 }
295                 talloc_free(mod_msg);
296         }
297
298         if (ret == LDB_ERR_OPERATIONS_ERROR || ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS || ret == LDB_ERR_INVALID_DN_SYNTAX) {
299                 /* We might be on a read-only DB or LDAP */
300                 ret = LDB_SUCCESS;
301         }
302         if (ret != LDB_SUCCESS) {
303                 DBG_ERR("Failed to set schema into @ATTRIBUTES: %s\n",
304                         ldb_errstring(ldb));
305                 talloc_free(mem_ctx);
306                 return ret;
307         }
308
309         /* Now write out the indexes, as found in the schema (if they have changed) */
310
311         ret = ldb_search(ldb, mem_ctx, &res_idx, msg_idx->dn, LDB_SCOPE_BASE,
312                          NULL, NULL);
313         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
314                 if (mode == SCHEMA_COMPARE) {
315                         /* We are probably not in a transaction */
316                         goto wrong_mode;
317                 }
318                 ret = ldb_add(ldb, msg_idx);
319         } else if (ret != LDB_SUCCESS) {
320         } else if (res_idx->count != 1) {
321                 if (mode == SCHEMA_COMPARE) {
322                         /* We are probably not in a transaction */
323                         goto wrong_mode;
324                 }
325                 ret = ldb_add(ldb, msg_idx);
326         } else {
327                 ret = LDB_SUCCESS;
328                 /* Annoyingly added to our search results */
329                 ldb_msg_remove_attr(res_idx->msgs[0], "distinguishedName");
330
331                 ret = ldb_msg_difference(ldb, mem_ctx,
332                                          res_idx->msgs[0], msg_idx, &mod_msg);
333                 if (ret != LDB_SUCCESS) {
334                         goto op_error;
335                 }
336
337                 /*
338                  * We don't want to re-index just because we didn't
339                  * see this flag
340                  *
341                  * DO NOT backport this logic earlier than 4.7, it
342                  * isn't needed and would be dangerous before 4.6,
343                  * where we add logic to samba_dsdb to manage
344                  * @SAMBA_FEATURES_SUPPORTED and need to know if the
345                  * DB has been re-opened by an earlier version.
346                  *
347                  */
348
349                 if (mod_msg->num_elements == 1
350                     && ldb_attr_cmp(mod_msg->elements[0].name,
351                                     SAMBA_FEATURES_SUPPORTED_FLAG) == 0) {
352                         /*
353                          * Ignore only adding
354                          * @SAMBA_FEATURES_SUPPORTED
355                          */
356                 } else if (mod_msg->num_elements > 0) {
357
358                         /*
359                          * Do the replace with the difference, as we
360                          * are under the read lock and we wish to do a
361                          * delete of any removed/renamed attributes
362                          */
363                         if (mode == SCHEMA_COMPARE) {
364                                 /* We are probably not in a transaction */
365                                 goto wrong_mode;
366                         }
367                         ret = dsdb_modify(ldb, mod_msg, 0);
368                 }
369                 talloc_free(mod_msg);
370         }
371         if (ret == LDB_ERR_OPERATIONS_ERROR || ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS || ret == LDB_ERR_INVALID_DN_SYNTAX) {
372                 /* We might be on a read-only DB */
373                 ret = LDB_SUCCESS;
374         }
375
376         if (ret != LDB_SUCCESS) {
377                 DBG_ERR("Failed to set schema into @INDEXLIST: %s\n",
378                         ldb_errstring(ldb));
379         }
380
381         talloc_free(mem_ctx);
382         return ret;
383
384 op_error:
385         talloc_free(mem_ctx);
386         return ldb_operr(ldb);
387
388 wrong_mode:
389         talloc_free(mem_ctx);
390         return LDB_ERR_BUSY;
391 }
392
393
394 /*
395   create extra attribute shortcuts
396  */
397 static void dsdb_setup_attribute_shortcuts(struct ldb_context *ldb, struct dsdb_schema *schema)
398 {
399         struct dsdb_attribute *attribute;
400
401         /* setup fast access to one_way_link and DN format */
402         for (attribute=schema->attributes; attribute; attribute=attribute->next) {
403                 attribute->dn_format = dsdb_dn_oid_to_format(attribute->syntax->ldap_oid);
404
405                 if (attribute->dn_format == DSDB_INVALID_DN) {
406                         attribute->one_way_link = false;
407                         continue;
408                 }
409
410                 /* these are not considered to be one way links for
411                    the purpose of DN link fixups */
412                 if (ldb_attr_cmp("distinguishedName", attribute->lDAPDisplayName) == 0 ||
413                     ldb_attr_cmp("objectCategory", attribute->lDAPDisplayName) == 0) {
414                         attribute->one_way_link = false;
415                         continue;
416                 }
417
418                 if (attribute->linkID == 0) {
419                         attribute->one_way_link = true;
420                         continue;
421                 }
422                 /* handle attributes with a linkID but no backlink */
423                 if ((attribute->linkID & 1) == 0 &&
424                     dsdb_attribute_by_linkID(schema, attribute->linkID + 1) == NULL) {
425                         attribute->one_way_link = true;
426                         continue;
427                 }
428                 attribute->one_way_link = false;
429         }
430 }
431
432 static int uint32_cmp(uint32_t c1, uint32_t c2)
433 {
434         if (c1 == c2) return 0;
435         return c1 > c2 ? 1 : -1;
436 }
437
438 static int dsdb_compare_class_by_lDAPDisplayName(struct dsdb_class **c1, struct dsdb_class **c2)
439 {
440         return strcasecmp((*c1)->lDAPDisplayName, (*c2)->lDAPDisplayName);
441 }
442 static int dsdb_compare_class_by_governsID_id(struct dsdb_class **c1, struct dsdb_class **c2)
443 {
444         return uint32_cmp((*c1)->governsID_id, (*c2)->governsID_id);
445 }
446 static int dsdb_compare_class_by_governsID_oid(struct dsdb_class **c1, struct dsdb_class **c2)
447 {
448         return strcasecmp((*c1)->governsID_oid, (*c2)->governsID_oid);
449 }
450 static int dsdb_compare_class_by_cn(struct dsdb_class **c1, struct dsdb_class **c2)
451 {
452         return strcasecmp((*c1)->cn, (*c2)->cn);
453 }
454
455 static int dsdb_compare_attribute_by_lDAPDisplayName(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
456 {
457         return strcasecmp((*a1)->lDAPDisplayName, (*a2)->lDAPDisplayName);
458 }
459 static int dsdb_compare_attribute_by_attributeID_id(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
460 {
461         return uint32_cmp((*a1)->attributeID_id, (*a2)->attributeID_id);
462 }
463 static int dsdb_compare_attribute_by_msDS_IntId(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
464 {
465         return uint32_cmp((*a1)->msDS_IntId, (*a2)->msDS_IntId);
466 }
467 static int dsdb_compare_attribute_by_attributeID_oid(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
468 {
469         return strcasecmp((*a1)->attributeID_oid, (*a2)->attributeID_oid);
470 }
471 static int dsdb_compare_attribute_by_linkID(struct dsdb_attribute **a1, struct dsdb_attribute **a2)
472 {
473         return uint32_cmp((*a1)->linkID, (*a2)->linkID);
474 }
475
476 /**
477  * Clean up Classes and Attributes accessor arrays
478  */
479 static void dsdb_sorted_accessors_free(struct dsdb_schema *schema)
480 {
481         /* free classes accessors */
482         TALLOC_FREE(schema->classes_by_lDAPDisplayName);
483         TALLOC_FREE(schema->classes_by_governsID_id);
484         TALLOC_FREE(schema->classes_by_governsID_oid);
485         TALLOC_FREE(schema->classes_by_cn);
486         /* free attribute accessors */
487         TALLOC_FREE(schema->attributes_by_lDAPDisplayName);
488         TALLOC_FREE(schema->attributes_by_attributeID_id);
489         TALLOC_FREE(schema->attributes_by_msDS_IntId);
490         TALLOC_FREE(schema->attributes_by_attributeID_oid);
491         TALLOC_FREE(schema->attributes_by_linkID);
492 }
493
494 /*
495   create the sorted accessor arrays for the schema
496  */
497 int dsdb_setup_sorted_accessors(struct ldb_context *ldb,
498                                 struct dsdb_schema *schema)
499 {
500         struct dsdb_class *cur;
501         struct dsdb_attribute *a;
502         unsigned int i;
503         unsigned int num_int_id;
504         int ret;
505
506         for (i=0; i < schema->classes_to_remove_size; i++) {
507                 DLIST_REMOVE(schema->classes, schema->classes_to_remove[i]);
508                 TALLOC_FREE(schema->classes_to_remove[i]);
509         }
510         for (i=0; i < schema->attributes_to_remove_size; i++) {
511                 DLIST_REMOVE(schema->attributes, schema->attributes_to_remove[i]);
512                 TALLOC_FREE(schema->attributes_to_remove[i]);
513         }
514
515         TALLOC_FREE(schema->classes_to_remove);
516         schema->classes_to_remove_size = 0;
517         TALLOC_FREE(schema->attributes_to_remove);
518         schema->attributes_to_remove_size = 0;
519
520         /* free all caches */
521         dsdb_sorted_accessors_free(schema);
522
523         /* count the classes */
524         for (i=0, cur=schema->classes; cur; i++, cur=cur->next) /* noop */ ;
525         schema->num_classes = i;
526
527         /* setup classes_by_* */
528         schema->classes_by_lDAPDisplayName = talloc_array(schema, struct dsdb_class *, i);
529         schema->classes_by_governsID_id    = talloc_array(schema, struct dsdb_class *, i);
530         schema->classes_by_governsID_oid   = talloc_array(schema, struct dsdb_class *, i);
531         schema->classes_by_cn              = talloc_array(schema, struct dsdb_class *, i);
532         if (schema->classes_by_lDAPDisplayName == NULL ||
533             schema->classes_by_governsID_id == NULL ||
534             schema->classes_by_governsID_oid == NULL ||
535             schema->classes_by_cn == NULL) {
536                 goto failed;
537         }
538
539         for (i=0, cur=schema->classes; cur; i++, cur=cur->next) {
540                 schema->classes_by_lDAPDisplayName[i] = cur;
541                 schema->classes_by_governsID_id[i]    = cur;
542                 schema->classes_by_governsID_oid[i]   = cur;
543                 schema->classes_by_cn[i]              = cur;
544         }
545
546         /* sort the arrays */
547         TYPESAFE_QSORT(schema->classes_by_lDAPDisplayName, schema->num_classes, dsdb_compare_class_by_lDAPDisplayName);
548         TYPESAFE_QSORT(schema->classes_by_governsID_id, schema->num_classes, dsdb_compare_class_by_governsID_id);
549         TYPESAFE_QSORT(schema->classes_by_governsID_oid, schema->num_classes, dsdb_compare_class_by_governsID_oid);
550         TYPESAFE_QSORT(schema->classes_by_cn, schema->num_classes, dsdb_compare_class_by_cn);
551
552         /* now build the attribute accessor arrays */
553
554         /* count the attributes
555          * and attributes with msDS-IntId set */
556         num_int_id = 0;
557         for (i=0, a=schema->attributes; a; i++, a=a->next) {
558                 if (a->msDS_IntId != 0) {
559                         num_int_id++;
560                 }
561         }
562         schema->num_attributes = i;
563         schema->num_int_id_attr = num_int_id;
564
565         /* setup attributes_by_* */
566         schema->attributes_by_lDAPDisplayName = talloc_array(schema, struct dsdb_attribute *, i);
567         schema->attributes_by_attributeID_id    = talloc_array(schema, struct dsdb_attribute *, i);
568         schema->attributes_by_msDS_IntId        = talloc_array(schema,
569                                                                struct dsdb_attribute *, num_int_id);
570         schema->attributes_by_attributeID_oid   = talloc_array(schema, struct dsdb_attribute *, i);
571         schema->attributes_by_linkID              = talloc_array(schema, struct dsdb_attribute *, i);
572         if (schema->attributes_by_lDAPDisplayName == NULL ||
573             schema->attributes_by_attributeID_id == NULL ||
574             schema->attributes_by_msDS_IntId == NULL ||
575             schema->attributes_by_attributeID_oid == NULL ||
576             schema->attributes_by_linkID == NULL) {
577                 goto failed;
578         }
579
580         num_int_id = 0;
581         for (i=0, a=schema->attributes; a; i++, a=a->next) {
582                 schema->attributes_by_lDAPDisplayName[i] = a;
583                 schema->attributes_by_attributeID_id[i]    = a;
584                 schema->attributes_by_attributeID_oid[i]   = a;
585                 schema->attributes_by_linkID[i]          = a;
586                 /* append attr-by-msDS-IntId values */
587                 if (a->msDS_IntId != 0) {
588                         schema->attributes_by_msDS_IntId[num_int_id] = a;
589                         num_int_id++;
590                 }
591         }
592         SMB_ASSERT(num_int_id == schema->num_int_id_attr);
593
594         /* sort the arrays */
595         TYPESAFE_QSORT(schema->attributes_by_lDAPDisplayName, schema->num_attributes, dsdb_compare_attribute_by_lDAPDisplayName);
596         TYPESAFE_QSORT(schema->attributes_by_attributeID_id, schema->num_attributes, dsdb_compare_attribute_by_attributeID_id);
597         TYPESAFE_QSORT(schema->attributes_by_msDS_IntId, schema->num_int_id_attr, dsdb_compare_attribute_by_msDS_IntId);
598         TYPESAFE_QSORT(schema->attributes_by_attributeID_oid, schema->num_attributes, dsdb_compare_attribute_by_attributeID_oid);
599         TYPESAFE_QSORT(schema->attributes_by_linkID, schema->num_attributes, dsdb_compare_attribute_by_linkID);
600
601         dsdb_setup_attribute_shortcuts(ldb, schema);
602
603         ret = schema_fill_constructed(schema);
604         if (ret != LDB_SUCCESS) {
605                 dsdb_sorted_accessors_free(schema);
606                 return ret;
607         }
608
609         return LDB_SUCCESS;
610
611 failed:
612         dsdb_sorted_accessors_free(schema);
613         return ldb_oom(ldb);
614 }
615
616 /**
617  * Attach the schema to an opaque pointer on the ldb,
618  * so ldb modules can find it
619  */
620 int dsdb_set_schema_refresh_function(struct ldb_context *ldb,
621                                      dsdb_schema_refresh_fn refresh_fn,
622                                      struct ldb_module *module)
623 {
624         int ret = ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", refresh_fn);
625         if (ret != LDB_SUCCESS) {
626                 return ret;
627         }
628
629         ret = ldb_set_opaque(ldb, "dsdb_schema_refresh_fn_private_data", module);
630         if (ret != LDB_SUCCESS) {
631                 return ret;
632         }
633         return LDB_SUCCESS;
634 }
635
636 /**
637  * Attach the schema to an opaque pointer on the ldb,
638  * so ldb modules can find it
639  */
640 int dsdb_set_schema(struct ldb_context *ldb,
641                     struct dsdb_schema *schema,
642                     enum schema_set_enum write_indices_and_attributes)
643 {
644         struct dsdb_schema *old_schema;
645         int ret;
646
647         ret = dsdb_setup_sorted_accessors(ldb, schema);
648         if (ret != LDB_SUCCESS) {
649                 return ret;
650         }
651
652         old_schema = ldb_get_opaque(ldb, "dsdb_schema");
653
654         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", NULL);
655         if (ret != LDB_SUCCESS) {
656                 return ret;
657         }
658
659         ret = ldb_set_opaque(ldb, "dsdb_schema", schema);
660         if (ret != LDB_SUCCESS) {
661                 return ret;
662         }
663
664         talloc_steal(ldb, schema);
665
666         /* Set the new attributes based on the new schema */
667         ret = dsdb_schema_set_indices_and_attributes(ldb, schema,
668                                                      write_indices_and_attributes);
669         if (ret != LDB_SUCCESS) {
670                 return ret;
671         }
672
673         /*
674          * Remove the reference to the schema we just overwrote - if there was
675          * none, NULL is harmless here.
676          */
677         if (old_schema != schema) {
678                 talloc_unlink(ldb, old_schema);
679         }
680
681         return ret;
682 }
683
684 /**
685  * Global variable to hold one copy of the schema, used to avoid memory bloat
686  */
687 static struct dsdb_schema *global_schema;
688
689 /**
690  * Make this ldb use a specified schema, already fully calculated and belonging to another ldb
691  *
692  * The write_indices_and_attributes controls writing of the @ records
693  * because we cannot write to a database that does not yet exist on
694  * disk.
695  */
696 int dsdb_reference_schema(struct ldb_context *ldb, struct dsdb_schema *schema,
697                           enum schema_set_enum write_indices_and_attributes)
698 {
699         int ret;
700         struct dsdb_schema *old_schema;
701         old_schema = ldb_get_opaque(ldb, "dsdb_schema");
702         ret = ldb_set_opaque(ldb, "dsdb_schema", schema);
703         if (ret != LDB_SUCCESS) {
704                 return ret;
705         }
706
707         /* Remove the reference to the schema we just overwrote - if there was
708          * none, NULL is harmless here */
709         talloc_unlink(ldb, old_schema);
710
711         if (talloc_reference(ldb, schema) == NULL) {
712                 return ldb_oom(ldb);
713         }
714
715         /* Make this ldb use local schema preferably */
716         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", NULL);
717         if (ret != LDB_SUCCESS) {
718                 return ret;
719         }
720
721         ret = ldb_set_opaque(ldb, "dsdb_refresh_fn", NULL);
722         if (ret != LDB_SUCCESS) {
723                 return ret;
724         }
725
726         ret = ldb_set_opaque(ldb, "dsdb_refresh_fn_private_data", NULL);
727         if (ret != LDB_SUCCESS) {
728                 return ret;
729         }
730
731         ret = dsdb_schema_set_indices_and_attributes(ldb, schema, write_indices_and_attributes);
732         if (ret != LDB_SUCCESS) {
733                 return ret;
734         }
735
736         return LDB_SUCCESS;
737 }
738
739 /**
740  * Make this ldb use the 'global' schema, setup to avoid having multiple copies in this process
741  */
742 int dsdb_set_global_schema(struct ldb_context *ldb)
743 {
744         int ret;
745         void *use_global_schema = (void *)1;
746         struct dsdb_schema *old_schema = ldb_get_opaque(ldb, "dsdb_schema");
747
748         ret = ldb_set_opaque(ldb, "dsdb_use_global_schema", use_global_schema);
749         if (ret != LDB_SUCCESS) {
750                 return ret;
751         }
752
753         if (global_schema == NULL) {
754                 return LDB_SUCCESS;
755         }
756
757         /* Remove any pointer to a previous schema */
758         ret = ldb_set_opaque(ldb, "dsdb_schema", NULL);
759         if (ret != LDB_SUCCESS) {
760                 return ret;
761         }
762
763         /* Remove the reference to the schema we just overwrote - if there was
764          * none, NULL is harmless here */
765         talloc_unlink(ldb, old_schema);
766
767         /* Set the new attributes based on the new schema */
768         /* Don't write indices and attributes, it's expensive */
769         ret = dsdb_schema_set_indices_and_attributes(ldb, global_schema, SCHEMA_MEMORY_ONLY);
770         if (ret == LDB_SUCCESS) {
771                 /* Keep a reference to this schema, just in case the original copy is replaced */
772                 if (talloc_reference(ldb, global_schema) == NULL) {
773                         return ldb_oom(ldb);
774                 }
775         }
776
777         return ret;
778 }
779
780 bool dsdb_uses_global_schema(struct ldb_context *ldb)
781 {
782         return (ldb_get_opaque(ldb, "dsdb_use_global_schema") != NULL);
783 }
784
785 /**
786  * Find the schema object for this ldb
787  *
788  * If reference_ctx is not NULL, then talloc_reference onto that context
789  */
790
791 struct dsdb_schema *dsdb_get_schema(struct ldb_context *ldb, TALLOC_CTX *reference_ctx)
792 {
793         const void *p;
794         struct dsdb_schema *schema_out = NULL;
795         struct dsdb_schema *schema_in = NULL;
796         dsdb_schema_refresh_fn refresh_fn;
797         struct ldb_module *loaded_from_module;
798         bool use_global_schema;
799         TALLOC_CTX *tmp_ctx = talloc_new(reference_ctx);
800         if (tmp_ctx == NULL) {
801                 return NULL;
802         }
803
804         /* see if we have a cached copy */
805         use_global_schema = dsdb_uses_global_schema(ldb);
806         if (use_global_schema) {
807                 schema_in = global_schema;
808         } else {
809                 p = ldb_get_opaque(ldb, "dsdb_schema");
810                 if (p != NULL) {
811                         schema_in = talloc_get_type_abort(p, struct dsdb_schema);
812                 }
813         }
814
815         refresh_fn = ldb_get_opaque(ldb, "dsdb_schema_refresh_fn");
816         if (refresh_fn) {
817                 loaded_from_module = ldb_get_opaque(ldb, "dsdb_schema_refresh_fn_private_data");
818
819                 SMB_ASSERT(loaded_from_module && (ldb_module_get_ctx(loaded_from_module) == ldb));
820         }
821
822         if (refresh_fn) {
823                 /* We need to guard against recursive calls here */
824                 if (ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", NULL) != LDB_SUCCESS) {
825                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
826                                       "dsdb_get_schema: clearing dsdb_schema_refresh_fn failed");
827                 } else {
828                         schema_out = refresh_fn(loaded_from_module,
829                                                 ldb_get_event_context(ldb),
830                                                 schema_in,
831                                                 use_global_schema);
832                 }
833                 if (ldb_set_opaque(ldb, "dsdb_schema_refresh_fn", refresh_fn) != LDB_SUCCESS) {
834                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
835                                       "dsdb_get_schema: re-setting dsdb_schema_refresh_fn failed");
836                 }
837                 if (!schema_out) {
838                         schema_out = schema_in;
839                         ldb_debug_set(ldb, LDB_DEBUG_FATAL,
840                                       "dsdb_get_schema: refresh_fn() failed");
841                 }
842         } else {
843                 schema_out = schema_in;
844         }
845
846         /* This removes the extra reference above */
847         talloc_free(tmp_ctx);
848         if (!reference_ctx) {
849                 return schema_out;
850         } else {
851                 return talloc_reference(reference_ctx, schema_out);
852         }
853 }
854
855 /**
856  * Make the schema found on this ldb the 'global' schema
857  */
858
859 void dsdb_make_schema_global(struct ldb_context *ldb, struct dsdb_schema *schema)
860 {
861         if (!schema) {
862                 return;
863         }
864
865         if (global_schema) {
866                 talloc_unlink(NULL, global_schema);
867         }
868
869         /* we want the schema to be around permanently */
870         talloc_reparent(ldb, NULL, schema);
871         global_schema = schema;
872
873         /* This calls the talloc_reference() of the global schema back onto the ldb */
874         dsdb_set_global_schema(ldb);
875 }
876
877 /**
878  * When loading the schema from LDIF files, we don't get the extended DNs.
879  *
880  * We need to set these up, so that from the moment we start the provision,
881  * the defaultObjectCategory links are set up correctly.
882  */
883 int dsdb_schema_fill_extended_dn(struct ldb_context *ldb, struct dsdb_schema *schema)
884 {
885         struct dsdb_class *cur;
886         const struct dsdb_class *target_class;
887         for (cur = schema->classes; cur; cur = cur->next) {
888                 const struct ldb_val *rdn;
889                 struct ldb_val guid;
890                 NTSTATUS status;
891                 struct ldb_dn *dn = ldb_dn_new(NULL, ldb, cur->defaultObjectCategory);
892
893                 if (!dn) {
894                         return LDB_ERR_INVALID_DN_SYNTAX;
895                 }
896                 rdn = ldb_dn_get_component_val(dn, 0);
897                 if (!rdn) {
898                         talloc_free(dn);
899                         return LDB_ERR_INVALID_DN_SYNTAX;
900                 }
901                 target_class = dsdb_class_by_cn_ldb_val(schema, rdn);
902                 if (!target_class) {
903                         talloc_free(dn);
904                         return LDB_ERR_CONSTRAINT_VIOLATION;
905                 }
906
907                 status = GUID_to_ndr_blob(&target_class->objectGUID, dn, &guid);
908                 if (!NT_STATUS_IS_OK(status)) {
909                         talloc_free(dn);
910                         return ldb_operr(ldb);
911                 }
912                 ldb_dn_set_extended_component(dn, "GUID", &guid);
913
914                 cur->defaultObjectCategory = ldb_dn_get_extended_linearized(cur, dn, 1);
915                 talloc_free(dn);
916         }
917         return LDB_SUCCESS;
918 }
919
920 /**
921  * @brief Add a new element to the schema and checks if it's a duplicate
922  *
923  * This function will add a new element to the schema and checks for existing
924  * duplicates.
925  *
926  * @param[in]  ldb                A pointer to an LDB context
927  *
928  * @param[in]  schema             A pointer to the dsdb_schema where the element
929  *                                will be added.
930  *
931  * @param[in]  msg                The ldb_message object representing the element
932  *                                to add.
933  *
934  * @param[in]  checkdups          A boolean to indicate if checks for duplicates
935  *                                should be done.
936  *
937  * @return                        A WERROR code
938  */
939 WERROR dsdb_schema_set_el_from_ldb_msg_dups(struct ldb_context *ldb, struct dsdb_schema *schema,
940                                             struct ldb_message *msg, bool checkdups)
941 {
942         const char* tstring;
943         time_t ts;
944         tstring = ldb_msg_find_attr_as_string(msg, "whenChanged", NULL);
945         /* keep a trace of the ts of the most recently changed object */
946         if (tstring) {
947                 ts = ldb_string_to_time(tstring);
948                 if (ts > schema->ts_last_change) {
949                         schema->ts_last_change = ts;
950                 }
951         }
952         if (samdb_find_attribute(ldb, msg,
953                                  "objectclass", "attributeSchema") != NULL) {
954
955                 return dsdb_set_attribute_from_ldb_dups(ldb, schema, msg, checkdups);
956         } else if (samdb_find_attribute(ldb, msg,
957                                  "objectclass", "classSchema") != NULL) {
958                 return dsdb_set_class_from_ldb_dups(schema, msg, checkdups);
959         }
960         /* Don't fail on things not classes or attributes */
961         return WERR_OK;
962 }
963
964 WERROR dsdb_schema_set_el_from_ldb_msg(struct ldb_context *ldb,
965                                        struct dsdb_schema *schema,
966                                        struct ldb_message *msg)
967 {
968         return dsdb_schema_set_el_from_ldb_msg_dups(ldb, schema, msg, false);
969 }
970
971 /**
972  * Rather than read a schema from the LDB itself, read it from an ldif
973  * file.  This allows schema to be loaded and used while adding the
974  * schema itself to the directory.
975  *
976  * Should be called with a transaction (or failing that, have no concurrent
977  * access while called).
978  */
979
980 WERROR dsdb_set_schema_from_ldif(struct ldb_context *ldb,
981                                  const char *pf, const char *df,
982                                  const char *dn)
983 {
984         struct ldb_ldif *ldif;
985         struct ldb_message *msg;
986         TALLOC_CTX *mem_ctx;
987         WERROR status;
988         int ret;
989         struct dsdb_schema *schema;
990         const struct ldb_val *prefix_val;
991         const struct ldb_val *info_val;
992         struct ldb_val info_val_default;
993
994
995         mem_ctx = talloc_new(ldb);
996         if (!mem_ctx) {
997                 goto nomem;
998         }
999
1000         schema = dsdb_new_schema(mem_ctx);
1001         if (!schema) {
1002                 goto nomem;
1003         }
1004         schema->fsmo.we_are_master = true;
1005         schema->fsmo.update_allowed = true;
1006         schema->fsmo.master_dn = ldb_dn_new(schema, ldb, "@PROVISION_SCHEMA_MASTER");
1007         if (!schema->fsmo.master_dn) {
1008                 goto nomem;
1009         }
1010
1011         /*
1012          * load the prefixMap attribute from pf
1013          */
1014         ldif = ldb_ldif_read_string(ldb, &pf);
1015         if (!ldif) {
1016                 status = WERR_INVALID_PARAMETER;
1017                 goto failed;
1018         }
1019         talloc_steal(mem_ctx, ldif);
1020
1021         ret = ldb_msg_normalize(ldb, mem_ctx, ldif->msg, &msg);
1022         if (ret != LDB_SUCCESS) {
1023                 goto nomem;
1024         }
1025         talloc_free(ldif);
1026
1027         prefix_val = ldb_msg_find_ldb_val(msg, "prefixMap");
1028         if (!prefix_val) {
1029                 status = WERR_INVALID_PARAMETER;
1030                 goto failed;
1031         }
1032
1033         info_val = ldb_msg_find_ldb_val(msg, "schemaInfo");
1034         if (!info_val) {
1035                 status = dsdb_schema_info_blob_new(mem_ctx, &info_val_default);
1036                 W_ERROR_NOT_OK_GOTO(status, failed);
1037                 info_val = &info_val_default;
1038         }
1039
1040         status = dsdb_load_oid_mappings_ldb(schema, prefix_val, info_val);
1041         if (!W_ERROR_IS_OK(status)) {
1042                 DEBUG(0,("ERROR: dsdb_load_oid_mappings_ldb() failed with %s\n", win_errstr(status)));
1043                 goto failed;
1044         }
1045
1046         schema->ts_last_change = 0;
1047         /* load the attribute and class definitions out of df */
1048         while ((ldif = ldb_ldif_read_string(ldb, &df))) {
1049                 talloc_steal(mem_ctx, ldif);
1050
1051                 ret = ldb_msg_normalize(ldb, ldif, ldif->msg, &msg);
1052                 if (ret != LDB_SUCCESS) {
1053                         goto nomem;
1054                 }
1055
1056                 status = dsdb_schema_set_el_from_ldb_msg(ldb, schema, msg);
1057                 talloc_free(ldif);
1058                 if (!W_ERROR_IS_OK(status)) {
1059                         goto failed;
1060                 }
1061         }
1062
1063         /*
1064          * TODO We may need a transaction here, otherwise this causes races.
1065          *
1066          * To do so may require an ldb_in_transaction function. In the
1067          * meantime, assume that this is always called with a transaction or in
1068          * isolation.
1069          */
1070         ret = dsdb_set_schema(ldb, schema, SCHEMA_WRITE);
1071         if (ret != LDB_SUCCESS) {
1072                 status = WERR_FOOBAR;
1073                 DEBUG(0,("ERROR: dsdb_set_schema() failed with %s / %s\n",
1074                          ldb_strerror(ret), ldb_errstring(ldb)));
1075                 goto failed;
1076         }
1077
1078         ret = dsdb_schema_fill_extended_dn(ldb, schema);
1079         if (ret != LDB_SUCCESS) {
1080                 status = WERR_FOOBAR;
1081                 goto failed;
1082         }
1083
1084         goto done;
1085
1086 nomem:
1087         status = WERR_NOT_ENOUGH_MEMORY;
1088 failed:
1089 done:
1090         talloc_free(mem_ctx);
1091         return status;
1092 }