dsdb_create_prefix_mapping() implementation checks for existing prefix maping in...
[kai/samba.git] / source4 / dsdb / schema / schema_init.c
1 /* 
2    Unix SMB/CIFS mplementation.
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
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20    
21 */
22
23 #include "includes.h"
24 #include "dsdb/samdb/samdb.h"
25 #include "lib/ldb/include/ldb_errors.h"
26 #include "lib/util/dlinklist.h"
27 #include "librpc/gen_ndr/ndr_misc.h"
28 #include "librpc/gen_ndr/ndr_drsuapi.h"
29 #include "librpc/gen_ndr/ndr_drsblobs.h"
30 #include "param/param.h"
31
32 struct dsdb_schema *dsdb_new_schema(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience)
33 {
34         struct dsdb_schema *schema = talloc_zero(mem_ctx, struct dsdb_schema);
35         if (!schema) {
36                 return NULL;
37         }
38
39         schema->iconv_convenience = iconv_convenience;
40         return schema;
41 }
42
43
44 WERROR dsdb_load_oid_mappings_drsuapi(struct dsdb_schema *schema, const struct drsuapi_DsReplicaOIDMapping_Ctr *ctr)
45 {
46         uint32_t i,j;
47
48         schema->prefixes = talloc_array(schema, struct dsdb_schema_oid_prefix, ctr->num_mappings);
49         W_ERROR_HAVE_NO_MEMORY(schema->prefixes);
50
51         for (i=0, j=0; i < ctr->num_mappings; i++) {
52                 if (ctr->mappings[i].oid.oid == NULL) {
53                         return WERR_INVALID_PARAM;
54                 }
55
56                 if (strncasecmp(ctr->mappings[i].oid.oid, "ff", 2) == 0) {
57                         if (ctr->mappings[i].id_prefix != 0) {
58                                 return WERR_INVALID_PARAM;
59                         }
60
61                         /* the magic value should be in the last array member */
62                         if (i != (ctr->num_mappings - 1)) {
63                                 return WERR_INVALID_PARAM;
64                         }
65
66                         if (ctr->mappings[i].oid.__ndr_size != 21) {
67                                 return WERR_INVALID_PARAM;
68                         }
69
70                         schema->schema_info = talloc_strdup(schema, ctr->mappings[i].oid.oid);
71                         W_ERROR_HAVE_NO_MEMORY(schema->schema_info);
72                 } else {
73                         /* the last array member should contain the magic value not a oid */
74                         if (i == (ctr->num_mappings - 1)) {
75                                 return WERR_INVALID_PARAM;
76                         }
77
78                         schema->prefixes[j].id  = ctr->mappings[i].id_prefix<<16;
79                         schema->prefixes[j].oid = talloc_asprintf(schema->prefixes, "%s.",
80                                                                   ctr->mappings[i].oid.oid);
81                         W_ERROR_HAVE_NO_MEMORY(schema->prefixes[j].oid);
82                         schema->prefixes[j].oid_len = strlen(schema->prefixes[j].oid);
83                         j++;
84                 }
85         }
86
87         schema->num_prefixes = j;
88         return WERR_OK;
89 }
90
91 WERROR dsdb_load_oid_mappings_ldb(struct dsdb_schema *schema,
92                                   const struct ldb_val *prefixMap,
93                                   const struct ldb_val *schemaInfo)
94 {
95         WERROR status;
96         enum ndr_err_code ndr_err;
97         struct prefixMapBlob pfm;
98         char *schema_info;
99
100         TALLOC_CTX *mem_ctx = talloc_new(schema);
101         W_ERROR_HAVE_NO_MEMORY(mem_ctx);
102         
103         ndr_err = ndr_pull_struct_blob(prefixMap, mem_ctx, schema->iconv_convenience, &pfm, (ndr_pull_flags_fn_t)ndr_pull_prefixMapBlob);
104         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
105                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
106                 talloc_free(mem_ctx);
107                 return ntstatus_to_werror(nt_status);
108         }
109
110         if (pfm.version != PREFIX_MAP_VERSION_DSDB) {
111                 talloc_free(mem_ctx);
112                 return WERR_FOOBAR;
113         }
114
115         if (schemaInfo->length != 21 && schemaInfo->data[0] == 0xFF) {
116                 talloc_free(mem_ctx);
117                 return WERR_FOOBAR;
118         }
119
120         /* append the schema info as last element */
121         pfm.ctr.dsdb.num_mappings++;
122         pfm.ctr.dsdb.mappings = talloc_realloc(mem_ctx, pfm.ctr.dsdb.mappings,
123                                                struct drsuapi_DsReplicaOIDMapping,
124                                                pfm.ctr.dsdb.num_mappings);
125         W_ERROR_HAVE_NO_MEMORY(pfm.ctr.dsdb.mappings);
126
127         schema_info = data_blob_hex_string(pfm.ctr.dsdb.mappings, schemaInfo);
128         W_ERROR_HAVE_NO_MEMORY(schema_info);
129
130         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].id_prefix          = 0;    
131         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].oid.__ndr_size     = schemaInfo->length;
132         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].oid.oid            = schema_info;
133
134         /* call the drsuapi version */
135         status = dsdb_load_oid_mappings_drsuapi(schema, &pfm.ctr.dsdb);
136         talloc_free(mem_ctx);
137
138         W_ERROR_NOT_OK_RETURN(status);
139
140         return WERR_OK;
141 }
142
143 WERROR dsdb_get_oid_mappings_drsuapi(const struct dsdb_schema *schema,
144                                      bool include_schema_info,
145                                      TALLOC_CTX *mem_ctx,
146                                      struct drsuapi_DsReplicaOIDMapping_Ctr **_ctr)
147 {
148         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
149         uint32_t i;
150
151         ctr = talloc(mem_ctx, struct drsuapi_DsReplicaOIDMapping_Ctr);
152         W_ERROR_HAVE_NO_MEMORY(ctr);
153
154         ctr->num_mappings       = schema->num_prefixes;
155         if (include_schema_info) ctr->num_mappings++;
156         ctr->mappings = talloc_array(schema, struct drsuapi_DsReplicaOIDMapping, ctr->num_mappings);
157         W_ERROR_HAVE_NO_MEMORY(ctr->mappings);
158
159         for (i=0; i < schema->num_prefixes; i++) {
160                 ctr->mappings[i].id_prefix      = schema->prefixes[i].id>>16;
161                 ctr->mappings[i].oid.oid        = talloc_strndup(ctr->mappings,
162                                                                  schema->prefixes[i].oid,
163                                                                  schema->prefixes[i].oid_len - 1);
164                 W_ERROR_HAVE_NO_MEMORY(ctr->mappings[i].oid.oid);
165         }
166
167         if (include_schema_info) {
168                 ctr->mappings[i].id_prefix      = 0;
169                 ctr->mappings[i].oid.oid        = talloc_strdup(ctr->mappings,
170                                                                 schema->schema_info);
171                 W_ERROR_HAVE_NO_MEMORY(ctr->mappings[i].oid.oid);
172         }
173
174         *_ctr = ctr;
175         return WERR_OK;
176 }
177
178 WERROR dsdb_get_oid_mappings_ldb(const struct dsdb_schema *schema,
179                                  TALLOC_CTX *mem_ctx,
180                                  struct ldb_val *prefixMap,
181                                  struct ldb_val *schemaInfo)
182 {
183         WERROR status;
184         enum ndr_err_code ndr_err;
185         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
186         struct prefixMapBlob pfm;
187
188         status = dsdb_get_oid_mappings_drsuapi(schema, false, mem_ctx, &ctr);
189         W_ERROR_NOT_OK_RETURN(status);
190
191         pfm.version     = PREFIX_MAP_VERSION_DSDB;
192         pfm.reserved    = 0;
193         pfm.ctr.dsdb    = *ctr;
194
195         ndr_err = ndr_push_struct_blob(prefixMap, mem_ctx, schema->iconv_convenience, &pfm, (ndr_push_flags_fn_t)ndr_push_prefixMapBlob);
196         talloc_free(ctr);
197         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
198                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
199                 return ntstatus_to_werror(nt_status);
200         }
201
202         *schemaInfo = strhex_to_data_blob(schema->schema_info);
203         W_ERROR_HAVE_NO_MEMORY(schemaInfo->data);
204         talloc_steal(mem_ctx, schemaInfo->data);
205
206         return WERR_OK;
207 }
208
209 WERROR dsdb_verify_oid_mappings_drsuapi(const struct dsdb_schema *schema, const struct drsuapi_DsReplicaOIDMapping_Ctr *ctr)
210 {
211         uint32_t i,j;
212
213         for (i=0; i < ctr->num_mappings; i++) {
214                 if (ctr->mappings[i].oid.oid == NULL) {
215                         return WERR_INVALID_PARAM;
216                 }
217
218                 if (strncasecmp(ctr->mappings[i].oid.oid, "ff", 2) == 0) {
219                         if (ctr->mappings[i].id_prefix != 0) {
220                                 return WERR_INVALID_PARAM;
221                         }
222
223                         /* the magic value should be in the last array member */
224                         if (i != (ctr->num_mappings - 1)) {
225                                 return WERR_INVALID_PARAM;
226                         }
227
228                         if (ctr->mappings[i].oid.__ndr_size != 21) {
229                                 return WERR_INVALID_PARAM;
230                         }
231
232                         if (strcasecmp(schema->schema_info, ctr->mappings[i].oid.oid) != 0) {
233                                 return WERR_DS_DRA_SCHEMA_MISMATCH;
234                         }
235                 } else {
236                         /* the last array member should contain the magic value not a oid */
237                         if (i == (ctr->num_mappings - 1)) {
238                                 return WERR_INVALID_PARAM;
239                         }
240
241                         for (j=0; j < schema->num_prefixes; j++) {
242                                 size_t oid_len;
243                                 if (schema->prefixes[j].id != (ctr->mappings[i].id_prefix<<16)) {
244                                         continue;
245                                 }
246
247                                 oid_len = strlen(ctr->mappings[i].oid.oid);
248
249                                 if (oid_len != (schema->prefixes[j].oid_len - 1)) {
250                                         return WERR_DS_DRA_SCHEMA_MISMATCH;
251                                 }
252
253                                 if (strncmp(ctr->mappings[i].oid.oid, schema->prefixes[j].oid, oid_len) != 0) {
254                                         return WERR_DS_DRA_SCHEMA_MISMATCH;                             
255                                 }
256
257                                 break;
258                         }
259
260                         if (j == schema->num_prefixes) {
261                                 return WERR_DS_DRA_SCHEMA_MISMATCH;                             
262                         }
263                 }
264         }
265
266         return WERR_OK;
267 }
268
269 WERROR dsdb_map_oid2int(const struct dsdb_schema *schema, const char *in, uint32_t *out)
270 {
271         return dsdb_find_prefix_for_oid(schema->num_prefixes, schema->prefixes, in, out);
272 }
273
274
275 WERROR dsdb_map_int2oid(const struct dsdb_schema *schema, uint32_t in, TALLOC_CTX *mem_ctx, const char **out)
276 {
277         uint32_t i;
278
279         for (i=0; i < schema->num_prefixes; i++) {
280                 const char *val;
281                 if (schema->prefixes[i].id != (in & 0xFFFF0000)) {
282                         continue;
283                 }
284
285                 val = talloc_asprintf(mem_ctx, "%s%u",
286                                       schema->prefixes[i].oid,
287                                       in & 0xFFFF);
288                 W_ERROR_HAVE_NO_MEMORY(val);
289
290                 *out = val;
291                 return WERR_OK;
292         }
293
294         return WERR_DS_NO_MSDS_INTID;
295 }
296
297 /*
298  * this function is called from within a ldb transaction from the schema_fsmo module
299  */
300 WERROR dsdb_create_prefix_mapping(struct ldb_context *ldb, struct dsdb_schema *schema, const char *full_oid)
301 {
302         WERROR status;
303         uint32_t num_prefixes;
304         struct dsdb_schema_oid_prefix *prefixes;
305         struct ldb_val ndr_blob;
306         TALLOC_CTX *mem_ctx;
307         uint32_t out;
308
309         mem_ctx = talloc_new(ldb);
310         W_ERROR_HAVE_NO_MEMORY(mem_ctx);
311
312         /* Read prefixes from disk*/
313         status = dsdb_read_prefixes_from_ldb( mem_ctx, ldb, &num_prefixes, &prefixes ); 
314         if (!W_ERROR_IS_OK(status)) {
315                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_read_prefixes_from_ldb failed\n"));
316                 talloc_free(mem_ctx);
317                 return status;
318         }
319
320         /* Check if there is a prefix for the oid in the prefixes array*/
321         status = dsdb_find_prefix_for_oid( num_prefixes, prefixes, full_oid, &out ); 
322         if (W_ERROR_IS_OK(status)) {
323                 /* prefix found*/
324                 talloc_free(mem_ctx);
325                 return status;
326         }
327         /* Update prefix map in ldb*/
328         /* Update the prefixes */
329         status = dsdb_prefix_map_update(mem_ctx, &num_prefixes, &prefixes, full_oid);
330         if (!W_ERROR_IS_OK(status)) {
331                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_prefix_map_update failed\n"));
332                 talloc_free(mem_ctx);
333                 return status;
334         }
335         /* Convert prefixes in ndr blob*/
336         status = dsdb_write_prefixes_to_ndr( mem_ctx, ldb, num_prefixes, prefixes, &ndr_blob );
337         if (!W_ERROR_IS_OK(status)) {
338                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_write_prefixes_to_ndr failed\n"));
339                 talloc_free(mem_ctx);
340                 return status;
341         }
342
343         /* Update prefixMap in ldb*/
344         status = dsdb_write_prefixes_to_ldb( mem_ctx, ldb, &ndr_blob );
345         if (!W_ERROR_IS_OK(status)) {
346                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_write_prefixes_to_ldb failed\n"));
347                 talloc_free(mem_ctx);
348                 return status;
349         }
350
351         talloc_free(mem_ctx);
352         return status;
353 }
354
355 WERROR dsdb_prefix_map_update(TALLOC_CTX *mem_ctx, uint32_t *num_prefixes, struct dsdb_schema_oid_prefix **prefixes, const char *oid)
356 {
357         uint32_t new_num_prefixes, index_new_prefix, new_entry_id;
358         const char* lastDotOffset;
359         size_t size;
360         
361         new_num_prefixes = *num_prefixes + 1;
362         index_new_prefix = *num_prefixes;
363         new_entry_id = (*num_prefixes)<<16;
364
365         /* Extract the prefix from the oid*/
366         lastDotOffset = strrchr(oid, '.');
367         if (lastDotOffset == NULL) {
368                 DEBUG(0,("dsdb_prefix_map_update: failed to find the last dot\n"));
369                 return WERR_NOT_FOUND;
370         }
371
372         /* Calculate the size of the remainig string that should be the prefix of it */
373         size = strlen(oid) - strlen(lastDotOffset);
374         if (size <= 0) {
375                 DEBUG(0,("dsdb_prefix_map_update: size of the remaining string invalid\n"));
376                 return WERR_FOOBAR;
377         }
378         /* Add one because we need to copy the dot */
379         size += 1;
380
381         /* Create a spot in the prefixMap for one more prefix*/
382         (*prefixes) = talloc_realloc(mem_ctx, *prefixes, struct dsdb_schema_oid_prefix, new_num_prefixes);
383         W_ERROR_HAVE_NO_MEMORY(*prefixes);
384
385         /* Add the new prefix entry*/
386         (*prefixes)[index_new_prefix].id = new_entry_id;
387         (*prefixes)[index_new_prefix].oid = talloc_strndup(mem_ctx, oid, size);
388         (*prefixes)[index_new_prefix].oid_len = strlen((*prefixes)[index_new_prefix].oid);
389
390         /* Increase num_prefixes because new prefix has been added */
391         ++(*num_prefixes);
392
393         return WERR_OK;
394 }
395
396 WERROR dsdb_find_prefix_for_oid(uint32_t num_prefixes, const struct dsdb_schema_oid_prefix *prefixes, const char *in, uint32_t *out)
397 {
398         uint32_t i;
399
400         for (i=0; i < num_prefixes; i++) {
401                 const char *val_str;
402                 char *end_str;
403                 unsigned val;
404
405                 if (strncmp(prefixes[i].oid, in, prefixes[i].oid_len) != 0) {
406                         continue;
407                 }
408
409                 val_str = in + prefixes[i].oid_len;
410                 end_str = NULL;
411                 errno = 0;
412
413                 if (val_str[0] == '\0') {
414                         return WERR_INVALID_PARAM;
415                 }
416
417                 /* two '.' chars are invalid */
418                 if (val_str[0] == '.') {
419                         return WERR_INVALID_PARAM;
420                 }
421
422                 val = strtoul(val_str, &end_str, 10);
423                 if (end_str[0] == '.' && end_str[1] != '\0') {
424                         /*
425                          * if it's a '.' and not the last char
426                          * then maybe an other mapping apply
427                          */
428                         continue;
429                 } else if (end_str[0] != '\0') {
430                         return WERR_INVALID_PARAM;
431                 } else if (val > 0xFFFF) {
432                         return WERR_INVALID_PARAM;
433                 }
434
435                 *out = prefixes[i].id | val;
436                 return WERR_OK;
437         }
438
439         return WERR_DS_NO_MSDS_INTID;
440 }
441
442 WERROR dsdb_write_prefixes_to_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, struct ldb_val *ndr_blob)
443 {
444         struct ldb_message msg;
445         struct ldb_dn *schema_dn;
446         struct ldb_message_element el;
447         int ret;
448         
449         schema_dn = samdb_schema_dn(ldb);
450         if (!schema_dn) {
451                 DEBUG(0,("dsdb_write_prefixes_to_ldb: no schema dn present\n"));        
452                 return WERR_FOOBAR;
453         }
454  
455         el.num_values = 1;
456         el.values = ndr_blob;
457         el.flags = LDB_FLAG_MOD_REPLACE;
458         el.name = talloc_strdup(mem_ctx, "prefixMap");
459  
460         msg.dn = ldb_dn_copy(mem_ctx, schema_dn);
461         msg.num_elements = 1;
462         msg.elements = &el;
463  
464         ret = ldb_modify( ldb, &msg );
465         if (ret != 0) {
466                 DEBUG(0,("dsdb_write_prefixes_to_ldb: ldb_modify failed\n"));   
467                 return WERR_FOOBAR;
468         }
469  
470         return WERR_OK;
471 }
472
473 WERROR dsdb_read_prefixes_from_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, uint32_t* num_prefixes, struct dsdb_schema_oid_prefix **prefixes)
474 {
475         struct prefixMapBlob *blob;
476         enum ndr_err_code ndr_err;
477         uint32_t i;
478         const struct ldb_val *prefix_val;
479         struct ldb_dn *schema_dn;
480         struct ldb_result *schema_res;
481         int ret;    
482         static const char *schema_attrs[] = {
483                 "prefixMap",
484                 NULL
485         };
486
487         schema_dn = samdb_schema_dn(ldb);
488         if (!schema_dn) {
489                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no schema dn present\n"));
490                 return WERR_FOOBAR;
491         }
492
493         ret = ldb_search(ldb, schema_dn, LDB_SCOPE_BASE,NULL, schema_attrs,&schema_res);
494         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
495                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefix map present\n"));
496                 return WERR_FOOBAR;
497         } else if (ret != LDB_SUCCESS) {
498                 DEBUG(0,("dsdb_read_prefixes_from_ldb: failed to search the schema head\n"));
499                 return WERR_FOOBAR;
500         }
501
502         prefix_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "prefixMap");
503         if (!prefix_val) {
504                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefixMap attribute found\n"));
505                 return WERR_FOOBAR;
506         }
507
508         blob = talloc(mem_ctx, struct prefixMapBlob);
509         W_ERROR_HAVE_NO_MEMORY(blob);
510
511         ndr_err = ndr_pull_struct_blob(prefix_val, blob, 
512                                            lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), 
513                                            blob,
514                                            (ndr_pull_flags_fn_t)ndr_pull_prefixMapBlob);
515         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
516                 DEBUG(0,("dsdb_read_prefixes_from_ldb: ndr_pull_struct_blob failed\n"));
517                 talloc_free(blob);
518                 return WERR_FOOBAR;
519         }
520
521         if (blob->version != PREFIX_MAP_VERSION_DSDB) {
522                 DEBUG(0,("dsdb_read_prefixes_from_ldb: blob->version incorect\n"));
523                 talloc_free(blob);
524                 return WERR_FOOBAR;
525         }
526         
527         *num_prefixes = blob->ctr.dsdb.num_mappings;
528         *prefixes = talloc_array(mem_ctx, struct dsdb_schema_oid_prefix, *num_prefixes);
529         if(!(*prefixes)) {
530                 talloc_free(blob);
531                 return WERR_NOMEM;
532         }
533         for (i=0; i < blob->ctr.dsdb.num_mappings; i++) {
534                 (*prefixes)[i].id = blob->ctr.dsdb.mappings[i].id_prefix<<16;
535                 (*prefixes)[i].oid = talloc_strdup(mem_ctx, blob->ctr.dsdb.mappings[i].oid.oid);
536                 (*prefixes)[i].oid = talloc_asprintf_append((*prefixes)[i].oid, "."); 
537                 (*prefixes)[i].oid_len = strlen(blob->ctr.dsdb.mappings[i].oid.oid);
538         }
539
540         talloc_free(blob);
541         return WERR_OK;
542 }
543
544
545 WERROR dsdb_write_prefixes_to_ndr(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, uint32_t num_prefixes, const struct dsdb_schema_oid_prefix *prefixes, struct ldb_val *out)
546 {
547         struct prefixMapBlob *blob;
548         enum ndr_err_code ndr_err;
549         uint32_t i;
550
551         blob = talloc_zero(mem_ctx, struct prefixMapBlob);
552         W_ERROR_HAVE_NO_MEMORY(blob);
553
554         blob->version = PREFIX_MAP_VERSION_DSDB;
555         blob->ctr.dsdb.num_mappings = num_prefixes;
556         blob->ctr.dsdb.mappings = talloc_realloc(blob,
557                                                                                         blob->ctr.dsdb.mappings,
558                                                                                         struct drsuapi_DsReplicaOIDMapping,
559                                                                                         blob->ctr.dsdb.num_mappings);
560         if (!blob->ctr.dsdb.mappings) {
561                 return WERR_NOMEM;
562         }
563
564         for (i=0; i < num_prefixes; i++) {
565                 blob->ctr.dsdb.mappings[i].id_prefix = prefixes[i].id>>16;
566                 blob->ctr.dsdb.mappings[i].oid.oid = talloc_strdup(blob->ctr.dsdb.mappings, prefixes[i].oid);
567         }
568
569         ndr_err = ndr_push_struct_blob(out, ldb,
570                                            lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
571                                            blob,
572                                            (ndr_push_flags_fn_t)ndr_push_prefixMapBlob);
573         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
574                 return WERR_FOOBAR;
575         }
576         
577         return WERR_OK;
578 }
579
580
581 #define GET_STRING_LDB(msg, attr, mem_ctx, p, elem, strict) do { \
582         (p)->elem = samdb_result_string(msg, attr, NULL);\
583         if (strict && (p)->elem == NULL) { \
584                 d_printf("%s: %s == NULL\n", __location__, attr); \
585                 return WERR_INVALID_PARAM; \
586         } \
587         talloc_steal(mem_ctx, (p)->elem); \
588 } while (0)
589
590 #define GET_STRING_LIST_LDB(msg, attr, mem_ctx, p, elem, strict) do {   \
591         int get_string_list_counter;                                    \
592         struct ldb_message_element *get_string_list_el = ldb_msg_find_element(msg, attr); \
593         if (get_string_list_el == NULL) {                               \
594                 if (strict) {                                           \
595                         d_printf("%s: %s == NULL\n", __location__, attr); \
596                         return WERR_INVALID_PARAM;                      \
597                 } else {                                                \
598                         (p)->elem = NULL;                               \
599                         break;                                          \
600                 }                                                       \
601         }                                                               \
602         (p)->elem = talloc_array(mem_ctx, const char *, get_string_list_el->num_values + 1); \
603         for (get_string_list_counter=0;                                 \
604              get_string_list_counter < get_string_list_el->num_values;  \
605              get_string_list_counter++) {                               \
606                 (p)->elem[get_string_list_counter] = talloc_strndup((p)->elem, \
607                                                                     (const char *)get_string_list_el->values[get_string_list_counter].data, \
608                                                                     get_string_list_el->values[get_string_list_counter].length); \
609                 if (!(p)->elem[get_string_list_counter]) {              \
610                         d_printf("%s: talloc_strndup failed for %s\n", __location__, attr); \
611                         return WERR_NOMEM;                              \
612                 }                                                       \
613                 (p)->elem[get_string_list_counter+1] = NULL;            \
614         }                                                               \
615         talloc_steal(mem_ctx, (p)->elem);                               \
616 } while (0)
617
618 #define GET_BOOL_LDB(msg, attr, p, elem, strict) do { \
619         const char *str; \
620         str = samdb_result_string(msg, attr, NULL);\
621         if (str == NULL) { \
622                 if (strict) { \
623                         d_printf("%s: %s == NULL\n", __location__, attr); \
624                         return WERR_INVALID_PARAM; \
625                 } else { \
626                         (p)->elem = false; \
627                 } \
628         } else if (strcasecmp("TRUE", str) == 0) { \
629                 (p)->elem = true; \
630         } else if (strcasecmp("FALSE", str) == 0) { \
631                 (p)->elem = false; \
632         } else { \
633                 d_printf("%s: %s == %s\n", __location__, attr, str); \
634                 return WERR_INVALID_PARAM; \
635         } \
636 } while (0)
637
638 #define GET_UINT32_LDB(msg, attr, p, elem) do { \
639         (p)->elem = samdb_result_uint(msg, attr, 0);\
640 } while (0)
641
642 #define GET_GUID_LDB(msg, attr, p, elem) do { \
643         (p)->elem = samdb_result_guid(msg, attr);\
644 } while (0)
645
646 #define GET_BLOB_LDB(msg, attr, mem_ctx, p, elem) do { \
647         const struct ldb_val *_val;\
648         _val = ldb_msg_find_ldb_val(msg, attr);\
649         if (_val) {\
650                 (p)->elem = *_val;\
651                 talloc_steal(mem_ctx, (p)->elem.data);\
652         } else {\
653                 ZERO_STRUCT((p)->elem);\
654         }\
655 } while (0)
656
657 WERROR dsdb_attribute_from_ldb(const struct dsdb_schema *schema,
658                                struct ldb_message *msg,
659                                TALLOC_CTX *mem_ctx,
660                                struct dsdb_attribute *attr)
661 {
662         WERROR status;
663
664         GET_STRING_LDB(msg, "cn", mem_ctx, attr, cn, false);
665         GET_STRING_LDB(msg, "lDAPDisplayName", mem_ctx, attr, lDAPDisplayName, true);
666         GET_STRING_LDB(msg, "attributeID", mem_ctx, attr, attributeID_oid, true);
667         if (schema->num_prefixes == 0) {
668                 /* set an invalid value */
669                 attr->attributeID_id = 0xFFFFFFFF;
670         } else {
671                 status = dsdb_map_oid2int(schema, attr->attributeID_oid, &attr->attributeID_id);
672                 if (!W_ERROR_IS_OK(status)) {
673                         DEBUG(0,("%s: '%s': unable to map attributeID %s: %s\n",
674                                 __location__, attr->lDAPDisplayName, attr->attributeID_oid,
675                                 win_errstr(status)));
676                         return status;
677                 }
678         }
679         GET_GUID_LDB(msg, "schemaIDGUID", attr, schemaIDGUID);
680         GET_UINT32_LDB(msg, "mAPIID", attr, mAPIID);
681
682         GET_GUID_LDB(msg, "attributeSecurityGUID", attr, attributeSecurityGUID);
683
684         GET_UINT32_LDB(msg, "searchFlags", attr, searchFlags);
685         GET_UINT32_LDB(msg, "systemFlags", attr, systemFlags);
686         GET_BOOL_LDB(msg, "isMemberOfPartialAttributeSet", attr, isMemberOfPartialAttributeSet, false);
687         GET_UINT32_LDB(msg, "linkID", attr, linkID);
688
689         GET_STRING_LDB(msg, "attributeSyntax", mem_ctx, attr, attributeSyntax_oid, true);
690         if (schema->num_prefixes == 0) {
691                 /* set an invalid value */
692                 attr->attributeSyntax_id = 0xFFFFFFFF;
693         } else {
694                 status = dsdb_map_oid2int(schema, attr->attributeSyntax_oid, &attr->attributeSyntax_id);
695                 if (!W_ERROR_IS_OK(status)) {
696                         DEBUG(0,("%s: '%s': unable to map attributeSyntax_ %s: %s\n",
697                                 __location__, attr->lDAPDisplayName, attr->attributeSyntax_oid,
698                                 win_errstr(status)));
699                         return status;
700                 }
701         }
702         GET_UINT32_LDB(msg, "oMSyntax", attr, oMSyntax);
703         GET_BLOB_LDB(msg, "oMObjectClass", mem_ctx, attr, oMObjectClass);
704
705         GET_BOOL_LDB(msg, "isSingleValued", attr, isSingleValued, true);
706         GET_UINT32_LDB(msg, "rangeLower", attr, rangeLower);
707         GET_UINT32_LDB(msg, "rangeUpper", attr, rangeUpper);
708         GET_BOOL_LDB(msg, "extendedCharsAllowed", attr, extendedCharsAllowed, false);
709
710         GET_UINT32_LDB(msg, "schemaFlagsEx", attr, schemaFlagsEx);
711         GET_BLOB_LDB(msg, "msDs-Schema-Extensions", mem_ctx, attr, msDs_Schema_Extensions);
712
713         GET_BOOL_LDB(msg, "showInAdvancedViewOnly", attr, showInAdvancedViewOnly, false);
714         GET_STRING_LDB(msg, "adminDisplayName", mem_ctx, attr, adminDisplayName, false);
715         GET_STRING_LDB(msg, "adminDescription", mem_ctx, attr, adminDescription, false);
716         GET_STRING_LDB(msg, "classDisplayName", mem_ctx, attr, classDisplayName, false);
717         GET_BOOL_LDB(msg, "isEphemeral", attr, isEphemeral, false);
718         GET_BOOL_LDB(msg, "isDefunct", attr, isDefunct, false);
719         GET_BOOL_LDB(msg, "systemOnly", attr, systemOnly, false);
720
721         attr->syntax = dsdb_syntax_for_attribute(attr);
722         if (!attr->syntax) {
723                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
724         }
725
726         return WERR_OK;
727 }
728
729 WERROR dsdb_class_from_ldb(const struct dsdb_schema *schema,
730                            struct ldb_message *msg,
731                            TALLOC_CTX *mem_ctx,
732                            struct dsdb_class *obj)
733 {
734         WERROR status;
735
736         GET_STRING_LDB(msg, "cn", mem_ctx, obj, cn, false);
737         GET_STRING_LDB(msg, "lDAPDisplayName", mem_ctx, obj, lDAPDisplayName, true);
738         GET_STRING_LDB(msg, "governsID", mem_ctx, obj, governsID_oid, true);
739         if (schema->num_prefixes == 0) {
740                 /* set an invalid value */
741                 obj->governsID_id = 0xFFFFFFFF;
742         } else {
743                 status = dsdb_map_oid2int(schema, obj->governsID_oid, &obj->governsID_id);
744                 if (!W_ERROR_IS_OK(status)) {
745                         DEBUG(0,("%s: '%s': unable to map governsID %s: %s\n",
746                                 __location__, obj->lDAPDisplayName, obj->governsID_oid,
747                                 win_errstr(status)));
748                         return status;
749                 }
750         }
751         GET_GUID_LDB(msg, "schemaIDGUID", obj, schemaIDGUID);
752
753         GET_UINT32_LDB(msg, "objectClassCategory", obj, objectClassCategory);
754         GET_STRING_LDB(msg, "rDNAttID", mem_ctx, obj, rDNAttID, false);
755         GET_STRING_LDB(msg, "defaultObjectCategory", mem_ctx, obj, defaultObjectCategory, true);
756  
757         GET_STRING_LDB(msg, "subClassOf", mem_ctx, obj, subClassOf, true);
758
759         GET_STRING_LIST_LDB(msg, "systemAuxiliaryClass", mem_ctx, obj, systemAuxiliaryClass, false);
760         GET_STRING_LIST_LDB(msg, "auxiliaryClass", mem_ctx, obj, auxiliaryClass, false);
761
762         GET_STRING_LIST_LDB(msg, "systemMustContain", mem_ctx, obj, systemMustContain, false);
763         GET_STRING_LIST_LDB(msg, "systemMayContain", mem_ctx, obj, systemMayContain, false);
764         GET_STRING_LIST_LDB(msg, "mustContain", mem_ctx, obj, mustContain, false);
765         GET_STRING_LIST_LDB(msg, "mayContain", mem_ctx, obj, mayContain, false);
766
767         GET_STRING_LIST_LDB(msg, "systemPossSuperiors", mem_ctx, obj, systemPossSuperiors, false);
768         GET_STRING_LIST_LDB(msg, "possSuperiors", mem_ctx, obj, possSuperiors, false);
769         GET_STRING_LIST_LDB(msg, "possibleInferiors", mem_ctx, obj, possibleInferiors, false);
770
771         GET_STRING_LDB(msg, "defaultSecurityDescriptor", mem_ctx, obj, defaultSecurityDescriptor, false);
772
773         GET_UINT32_LDB(msg, "schemaFlagsEx", obj, schemaFlagsEx);
774         GET_BLOB_LDB(msg, "msDs-Schema-Extensions", mem_ctx, obj, msDs_Schema_Extensions);
775
776         GET_BOOL_LDB(msg, "showInAdvancedViewOnly", obj, showInAdvancedViewOnly, false);
777         GET_STRING_LDB(msg, "adminDisplayName", mem_ctx, obj, adminDisplayName, false);
778         GET_STRING_LDB(msg, "adminDescription", mem_ctx, obj, adminDescription, false);
779         GET_STRING_LDB(msg, "classDisplayName", mem_ctx, obj, classDisplayName, false);
780         GET_BOOL_LDB(msg, "defaultHidingValue", obj, defaultHidingValue, false);
781         GET_BOOL_LDB(msg, "isDefunct", obj, isDefunct, false);
782         GET_BOOL_LDB(msg, "systemOnly", obj, systemOnly, false);
783
784         return WERR_OK;
785 }
786
787 #define dsdb_oom(error_string, mem_ctx) *error_string = talloc_asprintf(mem_ctx, "dsdb out of memory at %s:%d\n", __FILE__, __LINE__)
788
789 int dsdb_schema_from_ldb_results(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
790                                  struct smb_iconv_convenience *iconv_convenience, 
791                                  struct ldb_result *schema_res,
792                                  struct ldb_result *attrs_res, struct ldb_result *objectclass_res, 
793                                  struct dsdb_schema **schema_out,
794                                  char **error_string)
795 {
796         WERROR status;
797         uint32_t i;
798         const struct ldb_val *prefix_val;
799         const struct ldb_val *info_val;
800         struct ldb_val info_val_default;
801         struct dsdb_schema *schema;
802
803         schema = dsdb_new_schema(mem_ctx, iconv_convenience);
804         if (!schema) {
805                 dsdb_oom(error_string, mem_ctx);
806                 return LDB_ERR_OPERATIONS_ERROR;
807         }
808
809         prefix_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "prefixMap");
810         if (!prefix_val) {
811                 *error_string = talloc_asprintf(mem_ctx, 
812                                                 "schema_fsmo_init: no prefixMap attribute found");
813                 talloc_free(mem_ctx);
814                 return LDB_ERR_CONSTRAINT_VIOLATION;
815         }
816         info_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "schemaInfo");
817         if (!info_val) {
818                 info_val_default = strhex_to_data_blob("FF0000000000000000000000000000000000000000");
819                 if (!info_val_default.data) {
820                         dsdb_oom(error_string, mem_ctx);
821                         return LDB_ERR_OPERATIONS_ERROR;
822                 }
823                 talloc_steal(mem_ctx, info_val_default.data);
824                 info_val = &info_val_default;
825         }
826
827         status = dsdb_load_oid_mappings_ldb(schema, prefix_val, info_val);
828         if (!W_ERROR_IS_OK(status)) {
829                 *error_string = talloc_asprintf(mem_ctx, 
830                               "schema_fsmo_init: failed to load oid mappings: %s",
831                               win_errstr(status));
832                 talloc_free(mem_ctx);
833                 return LDB_ERR_CONSTRAINT_VIOLATION;
834         }
835
836         for (i=0; i < attrs_res->count; i++) {
837                 struct dsdb_attribute *sa;
838
839                 sa = talloc_zero(schema, struct dsdb_attribute);
840                 if (!sa) {
841                         dsdb_oom(error_string, mem_ctx);
842                         return LDB_ERR_OPERATIONS_ERROR;
843                 }
844
845                 status = dsdb_attribute_from_ldb(schema, attrs_res->msgs[i], sa, sa);
846                 if (!W_ERROR_IS_OK(status)) {
847                         *error_string = talloc_asprintf(mem_ctx, 
848                                       "schema_fsmo_init: failed to load attribute definition: %s:%s",
849                                       ldb_dn_get_linearized(attrs_res->msgs[i]->dn),
850                                       win_errstr(status));
851                         talloc_free(mem_ctx);
852                         return LDB_ERR_CONSTRAINT_VIOLATION;
853                 }
854
855                 DLIST_ADD_END(schema->attributes, sa, struct dsdb_attribute *);
856         }
857
858         for (i=0; i < objectclass_res->count; i++) {
859                 struct dsdb_class *sc;
860
861                 sc = talloc_zero(schema, struct dsdb_class);
862                 if (!sc) {
863                         dsdb_oom(error_string, mem_ctx);
864                         return LDB_ERR_OPERATIONS_ERROR;
865                 }
866
867                 status = dsdb_class_from_ldb(schema, objectclass_res->msgs[i], sc, sc);
868                 if (!W_ERROR_IS_OK(status)) {
869                         *error_string = talloc_asprintf(mem_ctx, 
870                                       "schema_fsmo_init: failed to load class definition: %s:%s",
871                                       ldb_dn_get_linearized(objectclass_res->msgs[i]->dn),
872                                       win_errstr(status));
873                         talloc_free(mem_ctx);
874                         return LDB_ERR_CONSTRAINT_VIOLATION;
875                 }
876
877                 DLIST_ADD_END(schema->classes, sc, struct dsdb_class *);
878         }
879
880         schema->fsmo.master_dn = ldb_msg_find_attr_as_dn(ldb, schema, schema_res->msgs[0], "fSMORoleOwner");
881         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), schema->fsmo.master_dn) == 0) {
882                 schema->fsmo.we_are_master = true;
883         } else {
884                 schema->fsmo.we_are_master = false;
885         }
886
887         DEBUG(5, ("schema_fsmo_init: we are master: %s\n",
888                   (schema->fsmo.we_are_master?"yes":"no")));
889
890         *schema_out = schema;
891         return LDB_SUCCESS;
892 }
893
894 /* This recursive load of the objectClasses presumes that they
895  * everything is in a strict subClassOf hirarchy.  
896  *
897  * We load this in order so we produce certain outputs (such as the
898  * exported schema for openldap, and sorted objectClass attribute) 'in
899  * order' */
900
901 static int fetch_oc_recursive(struct ldb_context *ldb, struct ldb_dn *schemadn, 
902                               TALLOC_CTX *mem_ctx, 
903                               struct ldb_result *search_from,
904                               struct ldb_result *res_list)
905 {
906         int i;
907         int ret = 0;
908         for (i=0; i < search_from->count; i++) {
909                 struct ldb_result *res;
910                 const char *name = ldb_msg_find_attr_as_string(search_from->msgs[i], 
911                                                                "lDAPDisplayname", NULL);
912
913                 ret = ldb_search_exp_fmt(ldb, mem_ctx, &res,
914                                         schemadn, LDB_SCOPE_SUBTREE, NULL,
915                                         "(&(&(objectClass=classSchema)(subClassOf=%s))(!(lDAPDisplayName=%s)))",
916                                         name, name);
917                 if (ret != LDB_SUCCESS) {
918                         printf("Search failed: %s\n", ldb_errstring(ldb));
919                         return ret;
920                 }
921                 
922                 res_list->msgs = talloc_realloc(res_list, res_list->msgs, 
923                                                 struct ldb_message *, res_list->count + 2);
924                 if (!res_list->msgs) {
925                         return LDB_ERR_OPERATIONS_ERROR;
926                 }
927                 res_list->msgs[res_list->count] = talloc_move(res_list, 
928                                                               &search_from->msgs[i]);
929                 res_list->count++;
930                 res_list->msgs[res_list->count] = NULL;
931
932                 if (res->count > 0) {
933                         ret = fetch_oc_recursive(ldb, schemadn, mem_ctx, res, res_list); 
934                 }
935                 if (ret != LDB_SUCCESS) {
936                         return ret;
937                 }
938         }
939         return ret;
940 }
941
942 static int fetch_objectclass_schema(struct ldb_context *ldb, struct ldb_dn *schemadn, 
943                                     TALLOC_CTX *mem_ctx, 
944                                     struct ldb_result **objectclasses_res)
945 {
946         TALLOC_CTX *local_ctx = talloc_new(mem_ctx);
947         struct ldb_result *top_res, *ret_res;
948         int ret;
949         if (!local_ctx) {
950                 return LDB_ERR_OPERATIONS_ERROR;
951         }
952         
953         /* Downlaod 'top' */
954         ret = ldb_search(ldb, schemadn, LDB_SCOPE_SUBTREE, 
955                          "(&(objectClass=classSchema)(lDAPDisplayName=top))", 
956                          NULL, &top_res);
957         if (ret != LDB_SUCCESS) {
958                 printf("Search failed: %s\n", ldb_errstring(ldb));
959                 return LDB_ERR_OPERATIONS_ERROR;
960         }
961
962         talloc_steal(local_ctx, top_res);
963
964         if (top_res->count != 1) {
965                 return LDB_ERR_OPERATIONS_ERROR;
966         }
967
968         ret_res = talloc_zero(local_ctx, struct ldb_result);
969         if (!ret_res) {
970                 return LDB_ERR_OPERATIONS_ERROR;
971         }
972
973         ret = fetch_oc_recursive(ldb, schemadn, local_ctx, top_res, ret_res); 
974
975         if (ret != LDB_SUCCESS) {
976                 printf("Search failed: %s\n", ldb_errstring(ldb));
977                 return LDB_ERR_OPERATIONS_ERROR;
978         }
979
980         *objectclasses_res = talloc_move(mem_ctx, &ret_res);
981         return ret;
982 }
983
984 int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
985                                struct smb_iconv_convenience *iconv_convenience, 
986                                struct ldb_dn *schema_dn,
987                                struct dsdb_schema **schema,
988                                char **error_string_out) 
989 {
990         TALLOC_CTX *tmp_ctx;
991         char *error_string;
992         int ret;
993
994         struct ldb_result *schema_res;
995         struct ldb_result *a_res;
996         struct ldb_result *c_res;
997         static const char *schema_attrs[] = {
998                 "prefixMap",
999                 "schemaInfo",
1000                 "fSMORoleOwner",
1001                 NULL
1002         };
1003
1004         tmp_ctx = talloc_new(mem_ctx);
1005         if (!tmp_ctx) {
1006                 dsdb_oom(error_string_out, mem_ctx);
1007                 return LDB_ERR_OPERATIONS_ERROR;
1008         }
1009
1010         /*
1011          * setup the prefix mappings and schema info
1012          */
1013         ret = ldb_search(ldb, schema_dn,
1014                          LDB_SCOPE_BASE,
1015                          NULL, schema_attrs,
1016                          &schema_res);
1017         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1018                 talloc_free(tmp_ctx);
1019                 return ret;
1020         } else if (ret != LDB_SUCCESS) {
1021                 *error_string_out = talloc_asprintf(mem_ctx, 
1022                                        "dsdb_schema: failed to search the schema head: %s",
1023                                        ldb_errstring(ldb));
1024                 talloc_free(tmp_ctx);
1025                 return ret;
1026         }
1027         talloc_steal(tmp_ctx, schema_res);
1028         if (schema_res->count != 1) {
1029                 *error_string_out = talloc_asprintf(mem_ctx, 
1030                               "dsdb_schema: [%u] schema heads found on a base search",
1031                               schema_res->count);
1032                 talloc_free(tmp_ctx);
1033                 return LDB_ERR_CONSTRAINT_VIOLATION;
1034         }
1035
1036         /*
1037          * load the attribute definitions
1038          */
1039         ret = ldb_search(ldb, schema_dn,
1040                          LDB_SCOPE_ONELEVEL,
1041                          "(objectClass=attributeSchema)", NULL,
1042                          &a_res);
1043         if (ret != LDB_SUCCESS) {
1044                 *error_string_out = talloc_asprintf(mem_ctx, 
1045                                        "dsdb_schema: failed to search attributeSchema objects: %s",
1046                                        ldb_errstring(ldb));
1047                 talloc_free(tmp_ctx);
1048                 return ret;
1049         }
1050         talloc_steal(tmp_ctx, a_res);
1051
1052         /*
1053          * load the objectClass definitions
1054          */
1055         ret = fetch_objectclass_schema(ldb, schema_dn, tmp_ctx, &c_res);
1056         if (ret != LDB_SUCCESS) {
1057                 *error_string_out = talloc_asprintf(mem_ctx, 
1058                                        "Failed to fetch objectClass schema elements: %s\n", ldb_errstring(ldb));
1059                 talloc_free(tmp_ctx);
1060                 return ret;
1061         }
1062
1063         ret = dsdb_schema_from_ldb_results(tmp_ctx, ldb,
1064                                            lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
1065                                            schema_res, a_res, c_res, schema, &error_string);
1066         if (ret != LDB_SUCCESS) {
1067                 *error_string_out = talloc_asprintf(mem_ctx, 
1068                                                     "dsdb_schema load failed: %s",
1069                                                     error_string);
1070                 talloc_free(tmp_ctx);
1071                 return ret;
1072         }
1073         talloc_steal(mem_ctx, *schema);
1074         talloc_free(tmp_ctx);
1075
1076         return LDB_SUCCESS;
1077 }       
1078
1079
1080 static const struct {
1081         const char *name;
1082         const char *oid;
1083 } name_mappings[] = {
1084         { "cn",                                 "2.5.4.3" },
1085         { "name",                               "1.2.840.113556.1.4.1" },
1086         { "lDAPDisplayName",                    "1.2.840.113556.1.2.460" },
1087         { "attributeID",                        "1.2.840.113556.1.2.30" },
1088         { "schemaIDGUID",                       "1.2.840.113556.1.4.148" },
1089         { "mAPIID",                             "1.2.840.113556.1.2.49" },
1090         { "attributeSecurityGUID",              "1.2.840.113556.1.4.149" },
1091         { "searchFlags",                        "1.2.840.113556.1.2.334" },
1092         { "systemFlags",                        "1.2.840.113556.1.4.375" },
1093         { "isMemberOfPartialAttributeSet",      "1.2.840.113556.1.4.639" },
1094         { "linkID",                             "1.2.840.113556.1.2.50" },
1095         { "attributeSyntax",                    "1.2.840.113556.1.2.32" },
1096         { "oMSyntax",                           "1.2.840.113556.1.2.231" },
1097         { "oMObjectClass",                      "1.2.840.113556.1.2.218" },
1098         { "isSingleValued",                     "1.2.840.113556.1.2.33" },
1099         { "rangeLower",                         "1.2.840.113556.1.2.34" },
1100         { "rangeUpper",                         "1.2.840.113556.1.2.35" },
1101         { "extendedCharsAllowed",               "1.2.840.113556.1.2.380" },
1102         { "schemaFlagsEx",                      "1.2.840.113556.1.4.120" },
1103         { "msDs-Schema-Extensions",             "1.2.840.113556.1.4.1440" },
1104         { "showInAdvancedViewOnly",             "1.2.840.113556.1.2.169" },
1105         { "adminDisplayName",                   "1.2.840.113556.1.2.194" },
1106         { "adminDescription",                   "1.2.840.113556.1.2.226" },
1107         { "classDisplayName",                   "1.2.840.113556.1.4.610" },
1108         { "isEphemeral",                        "1.2.840.113556.1.4.1212" },
1109         { "isDefunct",                          "1.2.840.113556.1.4.661" },
1110         { "systemOnly",                         "1.2.840.113556.1.4.170" },
1111         { "governsID",                          "1.2.840.113556.1.2.22" },
1112         { "objectClassCategory",                "1.2.840.113556.1.2.370" },
1113         { "rDNAttID",                           "1.2.840.113556.1.2.26" },
1114         { "defaultObjectCategory",              "1.2.840.113556.1.4.783" },
1115         { "subClassOf",                         "1.2.840.113556.1.2.21" },
1116         { "systemAuxiliaryClass",               "1.2.840.113556.1.4.198" },
1117         { "systemPossSuperiors",                "1.2.840.113556.1.4.195" },
1118         { "systemMustContain",                  "1.2.840.113556.1.4.197" },
1119         { "systemMayContain",                   "1.2.840.113556.1.4.196" },
1120         { "auxiliaryClass",                     "1.2.840.113556.1.2.351" },
1121         { "possSuperiors",                      "1.2.840.113556.1.2.8" },
1122         { "mustContain",                        "1.2.840.113556.1.2.24" },
1123         { "mayContain",                         "1.2.840.113556.1.2.25" },
1124         { "defaultSecurityDescriptor",          "1.2.840.113556.1.4.224" },
1125         { "defaultHidingValue",                 "1.2.840.113556.1.4.518" },
1126 };
1127
1128 static struct drsuapi_DsReplicaAttribute *dsdb_find_object_attr_name(struct dsdb_schema *schema,
1129                                                                      struct drsuapi_DsReplicaObject *obj,
1130                                                                      const char *name,
1131                                                                      uint32_t *idx)
1132 {
1133         WERROR status;
1134         uint32_t i, id;
1135         const char *oid = NULL;
1136
1137         for(i=0; i < ARRAY_SIZE(name_mappings); i++) {
1138                 if (strcmp(name_mappings[i].name, name) != 0) continue;
1139
1140                 oid = name_mappings[i].oid;
1141                 break;
1142         }
1143
1144         if (!oid) {
1145                 return NULL;
1146         }
1147
1148         status = dsdb_map_oid2int(schema, oid, &id);
1149         if (!W_ERROR_IS_OK(status)) {
1150                 return NULL;
1151         }
1152
1153         for (i=0; i < obj->attribute_ctr.num_attributes; i++) {
1154                 if (obj->attribute_ctr.attributes[i].attid != id) continue;
1155
1156                 if (idx) *idx = i;
1157                 return &obj->attribute_ctr.attributes[i];
1158         }
1159
1160         return NULL;
1161 }
1162
1163 #define GET_STRING_DS(s, r, attr, mem_ctx, p, elem, strict) do { \
1164         struct drsuapi_DsReplicaAttribute *_a; \
1165         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1166         if (strict && !_a) { \
1167                 d_printf("%s: %s == NULL\n", __location__, attr); \
1168                 return WERR_INVALID_PARAM; \
1169         } \
1170         if (strict && _a->value_ctr.num_values != 1) { \
1171                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1172                         _a->value_ctr.num_values); \
1173                 return WERR_INVALID_PARAM; \
1174         } \
1175         if (_a && _a->value_ctr.num_values >= 1) { \
1176                 ssize_t _ret; \
1177                 _ret = convert_string_talloc(mem_ctx, s->iconv_convenience, CH_UTF16, CH_UNIX, \
1178                                              _a->value_ctr.values[0].blob->data, \
1179                                              _a->value_ctr.values[0].blob->length, \
1180                                              (void **)discard_const(&(p)->elem)); \
1181                 if (_ret == -1) { \
1182                         DEBUG(0,("%s: invalid data!\n", attr)); \
1183                         dump_data(0, \
1184                                      _a->value_ctr.values[0].blob->data, \
1185                                      _a->value_ctr.values[0].blob->length); \
1186                         return WERR_FOOBAR; \
1187                 } \
1188         } else { \
1189                 (p)->elem = NULL; \
1190         } \
1191 } while (0)
1192
1193 #define GET_DN_DS(s, r, attr, mem_ctx, p, elem, strict) do { \
1194         struct drsuapi_DsReplicaAttribute *_a; \
1195         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1196         if (strict && !_a) { \
1197                 d_printf("%s: %s == NULL\n", __location__, attr); \
1198                 return WERR_INVALID_PARAM; \
1199         } \
1200         if (strict && _a->value_ctr.num_values != 1) { \
1201                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1202                         _a->value_ctr.num_values); \
1203                 return WERR_INVALID_PARAM; \
1204         } \
1205         if (strict && !_a->value_ctr.values[0].blob) { \
1206                 d_printf("%s: %s data == NULL\n", __location__, attr); \
1207                 return WERR_INVALID_PARAM; \
1208         } \
1209         if (_a && _a->value_ctr.num_values >= 1 \
1210             && _a->value_ctr.values[0].blob) { \
1211                 struct drsuapi_DsReplicaObjectIdentifier3 _id3; \
1212                 enum ndr_err_code _ndr_err; \
1213                 _ndr_err = ndr_pull_struct_blob_all(_a->value_ctr.values[0].blob, \
1214                                                       mem_ctx, s->iconv_convenience, &_id3,\
1215                                                       (ndr_pull_flags_fn_t)ndr_pull_drsuapi_DsReplicaObjectIdentifier3);\
1216                 if (!NDR_ERR_CODE_IS_SUCCESS(_ndr_err)) { \
1217                         NTSTATUS _nt_status = ndr_map_error2ntstatus(_ndr_err); \
1218                         return ntstatus_to_werror(_nt_status); \
1219                 } \
1220                 (p)->elem = _id3.dn; \
1221         } else { \
1222                 (p)->elem = NULL; \
1223         } \
1224 } while (0)
1225
1226 #define GET_BOOL_DS(s, r, attr, p, elem, strict) do { \
1227         struct drsuapi_DsReplicaAttribute *_a; \
1228         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1229         if (strict && !_a) { \
1230                 d_printf("%s: %s == NULL\n", __location__, attr); \
1231                 return WERR_INVALID_PARAM; \
1232         } \
1233         if (strict && _a->value_ctr.num_values != 1) { \
1234                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1235                          (unsigned int)_a->value_ctr.num_values);       \
1236                 return WERR_INVALID_PARAM; \
1237         } \
1238         if (strict && !_a->value_ctr.values[0].blob) { \
1239                 d_printf("%s: %s data == NULL\n", __location__, attr); \
1240                 return WERR_INVALID_PARAM; \
1241         } \
1242         if (strict && _a->value_ctr.values[0].blob->length != 4) { \
1243                 d_printf("%s: %s length == %u\n", __location__, attr, \
1244                          (unsigned int)_a->value_ctr.values[0].blob->length); \
1245                 return WERR_INVALID_PARAM; \
1246         } \
1247         if (_a && _a->value_ctr.num_values >= 1 \
1248             && _a->value_ctr.values[0].blob \
1249             && _a->value_ctr.values[0].blob->length == 4) { \
1250                 (p)->elem = (IVAL(_a->value_ctr.values[0].blob->data,0)?true:false);\
1251         } else { \
1252                 (p)->elem = false; \
1253         } \
1254 } while (0)
1255
1256 #define GET_UINT32_DS(s, r, attr, p, elem) do { \
1257         struct drsuapi_DsReplicaAttribute *_a; \
1258         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1259         if (_a && _a->value_ctr.num_values >= 1 \
1260             && _a->value_ctr.values[0].blob \
1261             && _a->value_ctr.values[0].blob->length == 4) { \
1262                 (p)->elem = IVAL(_a->value_ctr.values[0].blob->data,0);\
1263         } else { \
1264                 (p)->elem = 0; \
1265         } \
1266 } while (0)
1267
1268 #define GET_GUID_DS(s, r, attr, mem_ctx, p, elem) do { \
1269         struct drsuapi_DsReplicaAttribute *_a; \
1270         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1271         if (_a && _a->value_ctr.num_values >= 1 \
1272             && _a->value_ctr.values[0].blob \
1273             && _a->value_ctr.values[0].blob->length == 16) { \
1274                 enum ndr_err_code _ndr_err; \
1275                 _ndr_err = ndr_pull_struct_blob_all(_a->value_ctr.values[0].blob, \
1276                                                       mem_ctx, s->iconv_convenience, &(p)->elem, \
1277                                                       (ndr_pull_flags_fn_t)ndr_pull_GUID); \
1278                 if (!NDR_ERR_CODE_IS_SUCCESS(_ndr_err)) { \
1279                         NTSTATUS _nt_status = ndr_map_error2ntstatus(_ndr_err); \
1280                         return ntstatus_to_werror(_nt_status); \
1281                 } \
1282         } else { \
1283                 ZERO_STRUCT((p)->elem);\
1284         } \
1285 } while (0)
1286
1287 #define GET_BLOB_DS(s, r, attr, mem_ctx, p, elem) do { \
1288         struct drsuapi_DsReplicaAttribute *_a; \
1289         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1290         if (_a && _a->value_ctr.num_values >= 1 \
1291             && _a->value_ctr.values[0].blob) { \
1292                 (p)->elem = *_a->value_ctr.values[0].blob;\
1293                 talloc_steal(mem_ctx, (p)->elem.data); \
1294         } else { \
1295                 ZERO_STRUCT((p)->elem);\
1296         }\
1297 } while (0)
1298
1299 WERROR dsdb_attribute_from_drsuapi(struct dsdb_schema *schema,
1300                                    struct drsuapi_DsReplicaObject *r,
1301                                    TALLOC_CTX *mem_ctx,
1302                                    struct dsdb_attribute *attr)
1303 {
1304         WERROR status;
1305
1306         GET_STRING_DS(schema, r, "name", mem_ctx, attr, cn, true);
1307         GET_STRING_DS(schema, r, "lDAPDisplayName", mem_ctx, attr, lDAPDisplayName, true);
1308         GET_UINT32_DS(schema, r, "attributeID", attr, attributeID_id);
1309         status = dsdb_map_int2oid(schema, attr->attributeID_id, mem_ctx, &attr->attributeID_oid);
1310         if (!W_ERROR_IS_OK(status)) {
1311                 DEBUG(0,("%s: '%s': unable to map attributeID 0x%08X: %s\n",
1312                         __location__, attr->lDAPDisplayName, attr->attributeID_id,
1313                         win_errstr(status)));
1314                 return status;
1315         }
1316         GET_GUID_DS(schema, r, "schemaIDGUID", mem_ctx, attr, schemaIDGUID);
1317         GET_UINT32_DS(schema, r, "mAPIID", attr, mAPIID);
1318
1319         GET_GUID_DS(schema, r, "attributeSecurityGUID", mem_ctx, attr, attributeSecurityGUID);
1320
1321         GET_UINT32_DS(schema, r, "searchFlags", attr, searchFlags);
1322         GET_UINT32_DS(schema, r, "systemFlags", attr, systemFlags);
1323         GET_BOOL_DS(schema, r, "isMemberOfPartialAttributeSet", attr, isMemberOfPartialAttributeSet, false);
1324         GET_UINT32_DS(schema, r, "linkID", attr, linkID);
1325
1326         GET_UINT32_DS(schema, r, "attributeSyntax", attr, attributeSyntax_id);
1327         status = dsdb_map_int2oid(schema, attr->attributeSyntax_id, mem_ctx, &attr->attributeSyntax_oid);
1328         if (!W_ERROR_IS_OK(status)) {
1329                 DEBUG(0,("%s: '%s': unable to map attributeSyntax 0x%08X: %s\n",
1330                         __location__, attr->lDAPDisplayName, attr->attributeSyntax_id,
1331                         win_errstr(status)));
1332                 return status;
1333         }
1334         GET_UINT32_DS(schema, r, "oMSyntax", attr, oMSyntax);
1335         GET_BLOB_DS(schema, r, "oMObjectClass", mem_ctx, attr, oMObjectClass);
1336
1337         GET_BOOL_DS(schema, r, "isSingleValued", attr, isSingleValued, true);
1338         GET_UINT32_DS(schema, r, "rangeLower", attr, rangeLower);
1339         GET_UINT32_DS(schema, r, "rangeUpper", attr, rangeUpper);
1340         GET_BOOL_DS(schema, r, "extendedCharsAllowed", attr, extendedCharsAllowed, false);
1341
1342         GET_UINT32_DS(schema, r, "schemaFlagsEx", attr, schemaFlagsEx);
1343         GET_BLOB_DS(schema, r, "msDs-Schema-Extensions", mem_ctx, attr, msDs_Schema_Extensions);
1344
1345         GET_BOOL_DS(schema, r, "showInAdvancedViewOnly", attr, showInAdvancedViewOnly, false);
1346         GET_STRING_DS(schema, r, "adminDisplayName", mem_ctx, attr, adminDisplayName, false);
1347         GET_STRING_DS(schema, r, "adminDescription", mem_ctx, attr, adminDescription, false);
1348         GET_STRING_DS(schema, r, "classDisplayName", mem_ctx, attr, classDisplayName, false);
1349         GET_BOOL_DS(schema, r, "isEphemeral", attr, isEphemeral, false);
1350         GET_BOOL_DS(schema, r, "isDefunct", attr, isDefunct, false);
1351         GET_BOOL_DS(schema, r, "systemOnly", attr, systemOnly, false);
1352
1353         attr->syntax = dsdb_syntax_for_attribute(attr);
1354         if (!attr->syntax) {
1355                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
1356         }
1357
1358         return WERR_OK;
1359 }
1360
1361 WERROR dsdb_class_from_drsuapi(struct dsdb_schema *schema,
1362                                struct drsuapi_DsReplicaObject *r,
1363                                TALLOC_CTX *mem_ctx,
1364                                struct dsdb_class *obj)
1365 {
1366         WERROR status;
1367
1368         GET_STRING_DS(schema, r, "name", mem_ctx, obj, cn, true);
1369         GET_STRING_DS(schema, r, "lDAPDisplayName", mem_ctx, obj, lDAPDisplayName, true);
1370         GET_UINT32_DS(schema, r, "governsID", obj, governsID_id);
1371         status = dsdb_map_int2oid(schema, obj->governsID_id, mem_ctx, &obj->governsID_oid);
1372         if (!W_ERROR_IS_OK(status)) {
1373                 DEBUG(0,("%s: '%s': unable to map governsID 0x%08X: %s\n",
1374                         __location__, obj->lDAPDisplayName, obj->governsID_id,
1375                         win_errstr(status)));
1376                 return status;
1377         }
1378         GET_GUID_DS(schema, r, "schemaIDGUID", mem_ctx, obj, schemaIDGUID);
1379
1380         GET_UINT32_DS(schema, r, "objectClassCategory", obj, objectClassCategory);
1381         GET_STRING_DS(schema, r, "rDNAttID", mem_ctx, obj, rDNAttID, false);
1382         GET_DN_DS(schema, r, "defaultObjectCategory", mem_ctx, obj, defaultObjectCategory, true);
1383
1384         GET_STRING_DS(schema, r, "subClassOf", mem_ctx, obj, subClassOf, true);
1385
1386         obj->systemAuxiliaryClass       = NULL;
1387         obj->systemPossSuperiors        = NULL;
1388         obj->systemMustContain          = NULL;
1389         obj->systemMayContain           = NULL;
1390
1391         obj->auxiliaryClass             = NULL;
1392         obj->possSuperiors              = NULL;
1393         obj->mustContain                = NULL;
1394         obj->mayContain                 = NULL;
1395
1396         obj->possibleInferiors          = NULL;
1397
1398         GET_STRING_DS(schema, r, "defaultSecurityDescriptor", mem_ctx, obj, defaultSecurityDescriptor, false);
1399
1400         GET_UINT32_DS(schema, r, "schemaFlagsEx", obj, schemaFlagsEx);
1401         GET_BLOB_DS(schema, r, "msDs-Schema-Extensions", mem_ctx, obj, msDs_Schema_Extensions);
1402
1403         GET_BOOL_DS(schema, r, "showInAdvancedViewOnly", obj, showInAdvancedViewOnly, false);
1404         GET_STRING_DS(schema, r, "adminDisplayName", mem_ctx, obj, adminDisplayName, false);
1405         GET_STRING_DS(schema, r, "adminDescription", mem_ctx, obj, adminDescription, false);
1406         GET_STRING_DS(schema, r, "classDisplayName", mem_ctx, obj, classDisplayName, false);
1407         GET_BOOL_DS(schema, r, "defaultHidingValue", obj, defaultHidingValue, false);
1408         GET_BOOL_DS(schema, r, "isDefunct", obj, isDefunct, false);
1409         GET_BOOL_DS(schema, r, "systemOnly", obj, systemOnly, false);
1410
1411         return WERR_OK;
1412 }
1413
1414 const struct dsdb_attribute *dsdb_attribute_by_attributeID_id(const struct dsdb_schema *schema,
1415                                                               uint32_t id)
1416 {
1417         struct dsdb_attribute *cur;
1418
1419         /*
1420          * 0xFFFFFFFF is used as value when no mapping table is available,
1421          * so don't try to match with it
1422          */
1423         if (id == 0xFFFFFFFF) return NULL;
1424
1425         /* TODO: add binary search */
1426         for (cur = schema->attributes; cur; cur = cur->next) {
1427                 if (cur->attributeID_id != id) continue;
1428
1429                 return cur;
1430         }
1431
1432         return NULL;
1433 }
1434
1435 const struct dsdb_attribute *dsdb_attribute_by_attributeID_oid(const struct dsdb_schema *schema,
1436                                                                const char *oid)
1437 {
1438         struct dsdb_attribute *cur;
1439
1440         if (!oid) return NULL;
1441
1442         /* TODO: add binary search */
1443         for (cur = schema->attributes; cur; cur = cur->next) {
1444                 if (strcmp(cur->attributeID_oid, oid) != 0) continue;
1445
1446                 return cur;
1447         }
1448
1449         return NULL;
1450 }
1451
1452 const struct dsdb_attribute *dsdb_attribute_by_lDAPDisplayName(const struct dsdb_schema *schema,
1453                                                                const char *name)
1454 {
1455         struct dsdb_attribute *cur;
1456
1457         if (!name) return NULL;
1458
1459         /* TODO: add binary search */
1460         for (cur = schema->attributes; cur; cur = cur->next) {
1461                 if (strcasecmp(cur->lDAPDisplayName, name) != 0) continue;
1462
1463                 return cur;
1464         }
1465
1466         return NULL;
1467 }
1468
1469 const struct dsdb_attribute *dsdb_attribute_by_linkID(const struct dsdb_schema *schema,
1470                                                       int linkID)
1471 {
1472         struct dsdb_attribute *cur;
1473
1474         /* TODO: add binary search */
1475         for (cur = schema->attributes; cur; cur = cur->next) {
1476                 if (cur->linkID != linkID) continue;
1477
1478                 return cur;
1479         }
1480
1481         return NULL;
1482 }
1483
1484 const struct dsdb_class *dsdb_class_by_governsID_id(const struct dsdb_schema *schema,
1485                                                     uint32_t id)
1486 {
1487         struct dsdb_class *cur;
1488
1489         /*
1490          * 0xFFFFFFFF is used as value when no mapping table is available,
1491          * so don't try to match with it
1492          */
1493         if (id == 0xFFFFFFFF) return NULL;
1494
1495         /* TODO: add binary search */
1496         for (cur = schema->classes; cur; cur = cur->next) {
1497                 if (cur->governsID_id != id) continue;
1498
1499                 return cur;
1500         }
1501
1502         return NULL;
1503 }
1504
1505 const struct dsdb_class *dsdb_class_by_governsID_oid(const struct dsdb_schema *schema,
1506                                                      const char *oid)
1507 {
1508         struct dsdb_class *cur;
1509
1510         if (!oid) return NULL;
1511
1512         /* TODO: add binary search */
1513         for (cur = schema->classes; cur; cur = cur->next) {
1514                 if (strcmp(cur->governsID_oid, oid) != 0) continue;
1515
1516                 return cur;
1517         }
1518
1519         return NULL;
1520 }
1521
1522 const struct dsdb_class *dsdb_class_by_lDAPDisplayName(const struct dsdb_schema *schema,
1523                                                        const char *name)
1524 {
1525         struct dsdb_class *cur;
1526
1527         if (!name) return NULL;
1528
1529         /* TODO: add binary search */
1530         for (cur = schema->classes; cur; cur = cur->next) {
1531                 if (strcasecmp(cur->lDAPDisplayName, name) != 0) continue;
1532
1533                 return cur;
1534         }
1535
1536         return NULL;
1537 }
1538
1539 const struct dsdb_class *dsdb_class_by_cn(const struct dsdb_schema *schema,
1540                                           const char *cn)
1541 {
1542         struct dsdb_class *cur;
1543
1544         if (!cn) return NULL;
1545
1546         /* TODO: add binary search */
1547         for (cur = schema->classes; cur; cur = cur->next) {
1548                 if (strcasecmp(cur->cn, cn) != 0) continue;
1549
1550                 return cur;
1551         }
1552
1553         return NULL;
1554 }
1555
1556 const char *dsdb_lDAPDisplayName_by_id(const struct dsdb_schema *schema,
1557                                        uint32_t id)
1558 {
1559         const struct dsdb_attribute *a;
1560         const struct dsdb_class *c;
1561
1562         /* TODO: add binary search */
1563         a = dsdb_attribute_by_attributeID_id(schema, id);
1564         if (a) {
1565                 return a->lDAPDisplayName;
1566         }
1567
1568         c = dsdb_class_by_governsID_id(schema, id);
1569         if (c) {
1570                 return c->lDAPDisplayName;
1571         }
1572
1573         return NULL;
1574 }
1575
1576 /** 
1577     Return a list of linked attributes, in lDAPDisplayName format.
1578
1579     This may be used to determine if a modification would require
1580     backlinks to be updated, for example
1581 */
1582
1583 WERROR dsdb_linked_attribute_lDAPDisplayName_list(const struct dsdb_schema *schema, TALLOC_CTX *mem_ctx, const char ***attr_list_ret)
1584 {
1585         const char **attr_list = NULL;
1586         struct dsdb_attribute *cur;
1587         int i = 0;
1588         for (cur = schema->attributes; cur; cur = cur->next) {
1589                 if (cur->linkID == 0) continue;
1590                 
1591                 attr_list = talloc_realloc(mem_ctx, attr_list, const char *, i+2);
1592                 if (!attr_list) {
1593                         return WERR_NOMEM;
1594                 }
1595                 attr_list[i] = cur->lDAPDisplayName;
1596                 i++;
1597         }
1598         attr_list[i] = NULL;
1599         *attr_list_ret = attr_list;
1600         return WERR_OK;
1601 }
1602
1603 static char **merge_attr_list(TALLOC_CTX *mem_ctx, 
1604                               char **attrs, const char **new_attrs) 
1605 {
1606         char **ret_attrs;
1607         int i;
1608         size_t new_len, orig_len = str_list_length((const char **)attrs);
1609         if (!new_attrs) {
1610                 return attrs;
1611         }
1612
1613         ret_attrs = talloc_realloc(mem_ctx, 
1614                                    attrs, char *, orig_len + str_list_length(new_attrs) + 1);
1615         if (ret_attrs) {
1616                 for (i=0; i < str_list_length(new_attrs); i++) {
1617                         ret_attrs[orig_len + i] = new_attrs[i];
1618                 }
1619                 new_len = orig_len + str_list_length(new_attrs);
1620
1621                 ret_attrs[new_len] = NULL;
1622
1623         }
1624
1625         return ret_attrs;
1626 }
1627
1628 char **dsdb_full_attribute_list_internal(TALLOC_CTX *mem_ctx, 
1629                                          const struct dsdb_schema *schema, 
1630                                          const char **class_list,
1631                                          enum dsdb_attr_list_query query)
1632 {
1633         int i;
1634         const struct dsdb_class *class;
1635         
1636         char **attr_list = NULL;
1637         char **recursive_list;
1638
1639         for (i=0; class_list && class_list[i]; i++) {
1640                 class = dsdb_class_by_lDAPDisplayName(schema, class_list[i]);
1641                 
1642                 switch (query) {
1643                 case DSDB_SCHEMA_ALL_MAY:
1644                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mayContain);
1645                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMayContain);
1646                         break;
1647
1648                 case DSDB_SCHEMA_ALL_MUST:
1649                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mustContain);
1650                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMustContain);
1651                         break;
1652
1653                 case DSDB_SCHEMA_SYS_MAY:
1654                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMayContain);
1655                         break;
1656
1657                 case DSDB_SCHEMA_SYS_MUST:
1658                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMustContain);
1659                         break;
1660
1661                 case DSDB_SCHEMA_MAY:
1662                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mayContain);
1663                         break;
1664
1665                 case DSDB_SCHEMA_MUST:
1666                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mustContain);
1667                         break;
1668
1669                 case DSDB_SCHEMA_ALL:
1670                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mayContain);
1671                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMayContain);
1672                         attr_list = merge_attr_list(mem_ctx, attr_list, class->mustContain);
1673                         attr_list = merge_attr_list(mem_ctx, attr_list, class->systemMustContain);
1674                         break;
1675                 }
1676
1677                 recursive_list = dsdb_full_attribute_list_internal(mem_ctx, schema, 
1678                                                                    class->systemAuxiliaryClass, 
1679                                                                    query);
1680                 
1681                 attr_list = merge_attr_list(mem_ctx, attr_list, (const char **)recursive_list);
1682                 
1683                 recursive_list = dsdb_full_attribute_list_internal(mem_ctx, schema, 
1684                                                                    class->auxiliaryClass, 
1685                                                                    query);
1686
1687                 attr_list = merge_attr_list(mem_ctx, attr_list, (const char **)recursive_list);
1688                 
1689         }
1690         return attr_list;
1691 }
1692
1693 char **dsdb_full_attribute_list(TALLOC_CTX *mem_ctx, 
1694                                 const struct dsdb_schema *schema, 
1695                                 const char **class_list,
1696                                 enum dsdb_attr_list_query query)
1697 {
1698         char **attr_list = dsdb_full_attribute_list_internal(mem_ctx, schema, class_list, query);
1699         size_t new_len = str_list_length((const char **)attr_list);
1700
1701         /* Remove duplicates */
1702         if (new_len > 1) {
1703                 int i;
1704                 qsort(attr_list, new_len,
1705                       sizeof(*attr_list),
1706                       (comparison_fn_t)strcasecmp);
1707                 
1708                 for (i=1 ; i < new_len; i++) {
1709                         char **val1 = &attr_list[i-1];
1710                         char **val2 = &attr_list[i];
1711                         if (ldb_attr_cmp(*val1, *val2) == 0) {
1712                                 memmove(val1, val2, (new_len - i) * sizeof( *attr_list)); 
1713                                 new_len--;
1714                                 i--;
1715                         }
1716                 }
1717         }
1718         return attr_list;
1719 }
1720 /**
1721  * Attach the schema to an opaque pointer on the ldb, so ldb modules
1722  * can find it 
1723  */
1724
1725 int dsdb_set_schema(struct ldb_context *ldb, struct dsdb_schema *schema)
1726 {
1727         int ret;
1728
1729         ret = ldb_set_opaque(ldb, "dsdb_schema", schema);
1730         if (ret != LDB_SUCCESS) {
1731                 return ret;
1732         }
1733
1734         talloc_steal(ldb, schema);
1735
1736         return LDB_SUCCESS;
1737 }
1738
1739 /**
1740  * Global variable to hold one copy of the schema, used to avoid memory bloat
1741  */
1742 static struct dsdb_schema *global_schema;
1743
1744 /**
1745  * Make this ldb use the 'global' schema, setup to avoid having multiple copies in this process
1746  */
1747 int dsdb_set_global_schema(struct ldb_context *ldb)
1748 {
1749         int ret;
1750         if (!global_schema) {
1751                 return LDB_SUCCESS;
1752         }
1753         ret = ldb_set_opaque(ldb, "dsdb_schema", global_schema);
1754         if (ret != LDB_SUCCESS) {
1755                 return ret;
1756         }
1757
1758         return LDB_SUCCESS;
1759 }
1760
1761 /**
1762  * Find the schema object for this ldb
1763  */
1764
1765 struct dsdb_schema *dsdb_get_schema(struct ldb_context *ldb)
1766 {
1767         const void *p;
1768         struct dsdb_schema *schema;
1769
1770         /* see if we have a cached copy */
1771         p = ldb_get_opaque(ldb, "dsdb_schema");
1772         if (!p) {
1773                 return NULL;
1774         }
1775
1776         schema = talloc_get_type(p, struct dsdb_schema);
1777         if (!schema) {
1778                 return NULL;
1779         }
1780
1781         return schema;
1782 }
1783
1784 /**
1785  * Make the schema found on this ldb the 'global' schema
1786  */
1787
1788 void dsdb_make_schema_global(struct ldb_context *ldb)
1789 {
1790         struct dsdb_schema *schema = dsdb_get_schema(ldb);
1791         if (!schema) {
1792                 return;
1793         }
1794
1795         talloc_steal(talloc_autofree_context(), schema);
1796         global_schema = schema;
1797
1798         dsdb_set_global_schema(ldb);
1799 }
1800
1801
1802 /**
1803  * Rather than read a schema from the LDB itself, read it from an ldif
1804  * file.  This allows schema to be loaded and used while adding the
1805  * schema itself to the directory.
1806  */
1807
1808 WERROR dsdb_attach_schema_from_ldif_file(struct ldb_context *ldb, const char *pf, const char *df)
1809 {
1810         struct ldb_ldif *ldif;
1811         struct ldb_message *msg;
1812         TALLOC_CTX *mem_ctx;
1813         WERROR status;
1814         int ret;
1815         struct dsdb_schema *schema;
1816         const struct ldb_val *prefix_val;
1817         const struct ldb_val *info_val;
1818         struct ldb_val info_val_default;
1819
1820         mem_ctx = talloc_new(ldb);
1821         if (!mem_ctx) {
1822                 goto nomem;
1823         }
1824
1825         schema = dsdb_new_schema(mem_ctx, lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")));
1826
1827         schema->fsmo.we_are_master = true;
1828         schema->fsmo.master_dn = ldb_dn_new_fmt(schema, ldb, "@PROVISION_SCHEMA_MASTER");
1829         if (!schema->fsmo.master_dn) {
1830                 goto nomem;
1831         }
1832
1833         /*
1834          * load the prefixMap attribute from pf
1835          */
1836         ldif = ldb_ldif_read_string(ldb, &pf);
1837         if (!ldif) {
1838                 status = WERR_INVALID_PARAM;
1839                 goto failed;
1840         }
1841         talloc_steal(mem_ctx, ldif);
1842
1843         msg = ldb_msg_canonicalize(ldb, ldif->msg);
1844         if (!msg) {
1845                 goto nomem;
1846         }
1847         talloc_steal(mem_ctx, msg);
1848         talloc_free(ldif);
1849
1850         prefix_val = ldb_msg_find_ldb_val(msg, "prefixMap");
1851         if (!prefix_val) {
1852                 status = WERR_INVALID_PARAM;
1853                 goto failed;
1854         }
1855
1856         info_val = ldb_msg_find_ldb_val(msg, "schemaInfo");
1857         if (!info_val) {
1858                 info_val_default = strhex_to_data_blob("FF0000000000000000000000000000000000000000");
1859                 if (!info_val_default.data) {
1860                         goto nomem;
1861                 }
1862                 talloc_steal(mem_ctx, info_val_default.data);
1863                 info_val = &info_val_default;
1864         }
1865
1866         status = dsdb_load_oid_mappings_ldb(schema, prefix_val, info_val);
1867         if (!W_ERROR_IS_OK(status)) {
1868                 goto failed;
1869         }
1870
1871         /*
1872          * load the attribute and class definitions outof df
1873          */
1874         while ((ldif = ldb_ldif_read_string(ldb, &df))) {
1875                 bool is_sa;
1876                 bool is_sc;
1877
1878                 talloc_steal(mem_ctx, ldif);
1879
1880                 msg = ldb_msg_canonicalize(ldb, ldif->msg);
1881                 if (!msg) {
1882                         goto nomem;
1883                 }
1884
1885                 talloc_steal(mem_ctx, msg);
1886                 talloc_free(ldif);
1887
1888                 is_sa = ldb_msg_check_string_attribute(msg, "objectClass", "attributeSchema");
1889                 is_sc = ldb_msg_check_string_attribute(msg, "objectClass", "classSchema");
1890
1891                 if (is_sa) {
1892                         struct dsdb_attribute *sa;
1893
1894                         sa = talloc_zero(schema, struct dsdb_attribute);
1895                         if (!sa) {
1896                                 goto nomem;
1897                         }
1898
1899                         status = dsdb_attribute_from_ldb(schema, msg, sa, sa);
1900                         if (!W_ERROR_IS_OK(status)) {
1901                                 goto failed;
1902                         }
1903
1904                         DLIST_ADD_END(schema->attributes, sa, struct dsdb_attribute *);
1905                 } else if (is_sc) {
1906                         struct dsdb_class *sc;
1907
1908                         sc = talloc_zero(schema, struct dsdb_class);
1909                         if (!sc) {
1910                                 goto nomem;
1911                         }
1912
1913                         status = dsdb_class_from_ldb(schema, msg, sc, sc);
1914                         if (!W_ERROR_IS_OK(status)) {
1915                                 goto failed;
1916                         }
1917
1918                         DLIST_ADD_END(schema->classes, sc, struct dsdb_class *);
1919                 }
1920         }
1921
1922         ret = dsdb_set_schema(ldb, schema);
1923         if (ret != LDB_SUCCESS) {
1924                 status = WERR_FOOBAR;
1925                 goto failed;
1926         }
1927
1928         goto done;
1929
1930 nomem:
1931         status = WERR_NOMEM;
1932 failed:
1933 done:
1934         talloc_free(mem_ctx);
1935         return status;
1936 }