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