Merge branch 'master' of git://git.samba.org/samba
[sfrench/samba-autobuild/.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 #include "lib/ldb/include/ldb_module.h"
32
33 struct dsdb_schema *dsdb_new_schema(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience)
34 {
35         struct dsdb_schema *schema = talloc_zero(mem_ctx, struct dsdb_schema);
36         if (!schema) {
37                 return NULL;
38         }
39
40         schema->iconv_convenience = iconv_convenience;
41         return schema;
42 }
43
44
45 WERROR dsdb_load_oid_mappings_drsuapi(struct dsdb_schema *schema, const struct drsuapi_DsReplicaOIDMapping_Ctr *ctr)
46 {
47         uint32_t i,j;
48
49         schema->prefixes = talloc_array(schema, struct dsdb_schema_oid_prefix, ctr->num_mappings);
50         W_ERROR_HAVE_NO_MEMORY(schema->prefixes);
51
52         for (i=0, j=0; i < ctr->num_mappings; i++) {
53                 if (ctr->mappings[i].oid.oid == NULL) {
54                         return WERR_INVALID_PARAM;
55                 }
56
57                 if (strncasecmp(ctr->mappings[i].oid.oid, "ff", 2) == 0) {
58                         if (ctr->mappings[i].id_prefix != 0) {
59                                 return WERR_INVALID_PARAM;
60                         }
61
62                         /* the magic value should be in the last array member */
63                         if (i != (ctr->num_mappings - 1)) {
64                                 return WERR_INVALID_PARAM;
65                         }
66
67                         if (ctr->mappings[i].oid.__ndr_size != 21) {
68                                 return WERR_INVALID_PARAM;
69                         }
70
71                         schema->schema_info = talloc_strdup(schema, ctr->mappings[i].oid.oid);
72                         W_ERROR_HAVE_NO_MEMORY(schema->schema_info);
73                 } else {
74                         /* the last array member should contain the magic value not a oid */
75                         if (i == (ctr->num_mappings - 1)) {
76                                 return WERR_INVALID_PARAM;
77                         }
78
79                         schema->prefixes[j].id  = ctr->mappings[i].id_prefix<<16;
80                         schema->prefixes[j].oid = talloc_asprintf(schema->prefixes, "%s.",
81                                                                   ctr->mappings[i].oid.oid);
82                         W_ERROR_HAVE_NO_MEMORY(schema->prefixes[j].oid);
83                         schema->prefixes[j].oid_len = strlen(schema->prefixes[j].oid);
84                         j++;
85                 }
86         }
87
88         schema->num_prefixes = j;
89         return WERR_OK;
90 }
91
92 WERROR dsdb_load_oid_mappings_ldb(struct dsdb_schema *schema,
93                                   const struct ldb_val *prefixMap,
94                                   const struct ldb_val *schemaInfo)
95 {
96         WERROR status;
97         enum ndr_err_code ndr_err;
98         struct prefixMapBlob pfm;
99         char *schema_info;
100
101         TALLOC_CTX *mem_ctx = talloc_new(schema);
102         W_ERROR_HAVE_NO_MEMORY(mem_ctx);
103         
104         ndr_err = ndr_pull_struct_blob(prefixMap, mem_ctx, schema->iconv_convenience, &pfm, (ndr_pull_flags_fn_t)ndr_pull_prefixMapBlob);
105         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
106                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
107                 talloc_free(mem_ctx);
108                 return ntstatus_to_werror(nt_status);
109         }
110
111         if (pfm.version != PREFIX_MAP_VERSION_DSDB) {
112                 talloc_free(mem_ctx);
113                 return WERR_FOOBAR;
114         }
115
116         if (schemaInfo->length != 21 && schemaInfo->data[0] == 0xFF) {
117                 talloc_free(mem_ctx);
118                 return WERR_FOOBAR;
119         }
120
121         /* append the schema info as last element */
122         pfm.ctr.dsdb.num_mappings++;
123         pfm.ctr.dsdb.mappings = talloc_realloc(mem_ctx, pfm.ctr.dsdb.mappings,
124                                                struct drsuapi_DsReplicaOIDMapping,
125                                                pfm.ctr.dsdb.num_mappings);
126         W_ERROR_HAVE_NO_MEMORY(pfm.ctr.dsdb.mappings);
127
128         schema_info = data_blob_hex_string(pfm.ctr.dsdb.mappings, schemaInfo);
129         W_ERROR_HAVE_NO_MEMORY(schema_info);
130
131         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].id_prefix          = 0;    
132         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].oid.__ndr_size     = schemaInfo->length;
133         pfm.ctr.dsdb.mappings[pfm.ctr.dsdb.num_mappings - 1].oid.oid            = schema_info;
134
135         /* call the drsuapi version */
136         status = dsdb_load_oid_mappings_drsuapi(schema, &pfm.ctr.dsdb);
137         talloc_free(mem_ctx);
138
139         W_ERROR_NOT_OK_RETURN(status);
140
141         return WERR_OK;
142 }
143
144 WERROR dsdb_get_oid_mappings_drsuapi(const struct dsdb_schema *schema,
145                                      bool include_schema_info,
146                                      TALLOC_CTX *mem_ctx,
147                                      struct drsuapi_DsReplicaOIDMapping_Ctr **_ctr)
148 {
149         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
150         uint32_t i;
151
152         ctr = talloc(mem_ctx, struct drsuapi_DsReplicaOIDMapping_Ctr);
153         W_ERROR_HAVE_NO_MEMORY(ctr);
154
155         ctr->num_mappings       = schema->num_prefixes;
156         if (include_schema_info) ctr->num_mappings++;
157         ctr->mappings = talloc_array(schema, struct drsuapi_DsReplicaOIDMapping, ctr->num_mappings);
158         W_ERROR_HAVE_NO_MEMORY(ctr->mappings);
159
160         for (i=0; i < schema->num_prefixes; i++) {
161                 ctr->mappings[i].id_prefix      = schema->prefixes[i].id>>16;
162                 ctr->mappings[i].oid.oid        = talloc_strndup(ctr->mappings,
163                                                                  schema->prefixes[i].oid,
164                                                                  schema->prefixes[i].oid_len - 1);
165                 W_ERROR_HAVE_NO_MEMORY(ctr->mappings[i].oid.oid);
166         }
167
168         if (include_schema_info) {
169                 ctr->mappings[i].id_prefix      = 0;
170                 ctr->mappings[i].oid.oid        = talloc_strdup(ctr->mappings,
171                                                                 schema->schema_info);
172                 W_ERROR_HAVE_NO_MEMORY(ctr->mappings[i].oid.oid);
173         }
174
175         *_ctr = ctr;
176         return WERR_OK;
177 }
178
179 WERROR dsdb_get_oid_mappings_ldb(const struct dsdb_schema *schema,
180                                  TALLOC_CTX *mem_ctx,
181                                  struct ldb_val *prefixMap,
182                                  struct ldb_val *schemaInfo)
183 {
184         WERROR status;
185         enum ndr_err_code ndr_err;
186         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
187         struct prefixMapBlob pfm;
188
189         status = dsdb_get_oid_mappings_drsuapi(schema, false, mem_ctx, &ctr);
190         W_ERROR_NOT_OK_RETURN(status);
191
192         pfm.version     = PREFIX_MAP_VERSION_DSDB;
193         pfm.reserved    = 0;
194         pfm.ctr.dsdb    = *ctr;
195
196         ndr_err = ndr_push_struct_blob(prefixMap, mem_ctx, schema->iconv_convenience, &pfm, (ndr_push_flags_fn_t)ndr_push_prefixMapBlob);
197         talloc_free(ctr);
198         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
199                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
200                 return ntstatus_to_werror(nt_status);
201         }
202
203         *schemaInfo = strhex_to_data_blob(mem_ctx, schema->schema_info);
204         W_ERROR_HAVE_NO_MEMORY(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         TALLOC_CTX *mem_ctx;
306         uint32_t out;
307
308         mem_ctx = talloc_new(ldb);
309         W_ERROR_HAVE_NO_MEMORY(mem_ctx);
310
311         /* Read prefixes from disk*/
312         status = dsdb_read_prefixes_from_ldb( mem_ctx, ldb, &num_prefixes, &prefixes ); 
313         if (!W_ERROR_IS_OK(status)) {
314                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_read_prefixes_from_ldb: %s\n",
315                         win_errstr(status)));
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         } else if (!W_ERROR_EQUAL(WERR_DS_NO_MSDS_INTID, status)) {
327                 /* error */
328                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_find_prefix_for_oid: %s\n",
329                         win_errstr(status)));
330                 talloc_free(mem_ctx);
331                 return status;
332         }
333
334         /* Create the new mapping for the prefix of full_oid */
335         status = dsdb_prefix_map_update(mem_ctx, &num_prefixes, &prefixes, full_oid);
336         if (!W_ERROR_IS_OK(status)) {
337                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_prefix_map_update: %s\n",
338                         win_errstr(status)));
339                 talloc_free(mem_ctx);
340                 return status;
341         }
342
343         talloc_free(schema->prefixes);
344         schema->prefixes = talloc_steal(schema, prefixes);
345         schema->num_prefixes = num_prefixes;
346
347         /* Update prefixMap in ldb*/
348         status = dsdb_write_prefixes_from_schema_to_ldb(mem_ctx, ldb, schema);
349         if (!W_ERROR_IS_OK(status)) {
350                 DEBUG(0,("dsdb_create_prefix_mapping: dsdb_write_prefixes_to_ldb: %s\n",
351                         win_errstr(status)));
352                 talloc_free(mem_ctx);
353                 return status;
354         }
355
356         DEBUG(2,(__location__ " Added prefixMap %s - now have %u prefixes\n",
357                  full_oid, num_prefixes));
358
359         talloc_free(mem_ctx);
360         return status;
361 }
362
363 WERROR dsdb_prefix_map_update(TALLOC_CTX *mem_ctx, uint32_t *num_prefixes, struct dsdb_schema_oid_prefix **prefixes, const char *oid)
364 {
365         uint32_t new_num_prefixes, index_new_prefix, new_entry_id;
366         const char* lastDotOffset;
367         size_t size;
368         
369         new_num_prefixes = *num_prefixes + 1;
370         index_new_prefix = *num_prefixes;
371
372         /*
373          * this is the algorithm we use to create new mappings for now
374          *
375          * TODO: find what algorithm windows use
376          */
377         new_entry_id = (*num_prefixes)<<16;
378
379         /* Extract the prefix from the oid*/
380         lastDotOffset = strrchr(oid, '.');
381         if (lastDotOffset == NULL) {
382                 DEBUG(0,("dsdb_prefix_map_update: failed to find the last dot\n"));
383                 return WERR_NOT_FOUND;
384         }
385
386         /* Calculate the size of the remainig string that should be the prefix of it */
387         size = strlen(oid) - strlen(lastDotOffset);
388         if (size <= 0) {
389                 DEBUG(0,("dsdb_prefix_map_update: size of the remaining string invalid\n"));
390                 return WERR_FOOBAR;
391         }
392         /* Add one because we need to copy the dot */
393         size += 1;
394
395         /* Create a spot in the prefixMap for one more prefix*/
396         (*prefixes) = talloc_realloc(mem_ctx, *prefixes, struct dsdb_schema_oid_prefix, new_num_prefixes);
397         W_ERROR_HAVE_NO_MEMORY(*prefixes);
398
399         /* Add the new prefix entry*/
400         (*prefixes)[index_new_prefix].id = new_entry_id;
401         (*prefixes)[index_new_prefix].oid = talloc_strndup(mem_ctx, oid, size);
402         (*prefixes)[index_new_prefix].oid_len = strlen((*prefixes)[index_new_prefix].oid);
403
404         /* Increase num_prefixes because new prefix has been added */
405         ++(*num_prefixes);
406
407         return WERR_OK;
408 }
409
410 WERROR dsdb_find_prefix_for_oid(uint32_t num_prefixes, const struct dsdb_schema_oid_prefix *prefixes, const char *in, uint32_t *out)
411 {
412         uint32_t i;
413
414         for (i=0; i < num_prefixes; i++) {
415                 const char *val_str;
416                 char *end_str;
417                 unsigned val;
418
419                 if (strncmp(prefixes[i].oid, in, prefixes[i].oid_len) != 0) {
420                         continue;
421                 }
422
423                 val_str = in + prefixes[i].oid_len;
424                 end_str = NULL;
425                 errno = 0;
426
427                 if (val_str[0] == '\0') {
428                         return WERR_INVALID_PARAM;
429                 }
430
431                 /* two '.' chars are invalid */
432                 if (val_str[0] == '.') {
433                         return WERR_INVALID_PARAM;
434                 }
435
436                 val = strtoul(val_str, &end_str, 10);
437                 if (end_str[0] == '.' && end_str[1] != '\0') {
438                         /*
439                          * if it's a '.' and not the last char
440                          * then maybe an other mapping apply
441                          */
442                         continue;
443                 } else if (end_str[0] != '\0') {
444                         return WERR_INVALID_PARAM;
445                 } else if (val > 0xFFFF) {
446                         return WERR_INVALID_PARAM;
447                 }
448
449                 *out = prefixes[i].id | val;
450                 return WERR_OK;
451         }
452
453         DEBUG(5,(__location__ " Failed to find oid %s - have %u prefixes\n", in, num_prefixes));
454
455         return WERR_DS_NO_MSDS_INTID;
456 }
457
458 WERROR dsdb_write_prefixes_from_schema_to_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
459                                                      const struct dsdb_schema *schema)
460 {
461         struct ldb_message *msg = ldb_msg_new(mem_ctx);
462         struct ldb_dn *schema_dn;
463         struct prefixMapBlob pm;
464         struct ldb_val ndr_blob;
465         enum ndr_err_code ndr_err;
466         uint32_t i;
467         int ret;
468
469         if (!msg) {
470                 return WERR_NOMEM;
471         }
472         
473         schema_dn = samdb_schema_dn(ldb);
474         if (!schema_dn) {
475                 DEBUG(0,("dsdb_write_prefixes_from_schema_to_ldb: no schema dn present\n"));    
476                 return WERR_FOOBAR;
477         }
478
479         pm.version                      = PREFIX_MAP_VERSION_DSDB;
480         pm.ctr.dsdb.num_mappings        = schema->num_prefixes;
481         pm.ctr.dsdb.mappings            = talloc_array(msg,
482                                                 struct drsuapi_DsReplicaOIDMapping,
483                                                 pm.ctr.dsdb.num_mappings);
484         if (!pm.ctr.dsdb.mappings) {
485                 talloc_free(msg);
486                 return WERR_NOMEM;
487         }
488
489         for (i=0; i < schema->num_prefixes; i++) {
490                 pm.ctr.dsdb.mappings[i].id_prefix = schema->prefixes[i].id>>16;
491                 pm.ctr.dsdb.mappings[i].oid.oid = talloc_strdup(pm.ctr.dsdb.mappings, schema->prefixes[i].oid);
492         }
493
494         ndr_err = ndr_push_struct_blob(&ndr_blob, msg,
495                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
496                                        &pm,
497                                        (ndr_push_flags_fn_t)ndr_push_prefixMapBlob);
498         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
499                 talloc_free(msg);
500                 return WERR_FOOBAR;
501         }
502  
503         msg->dn = schema_dn;
504         ret = ldb_msg_add_value(msg, "prefixMap", &ndr_blob, NULL);
505         if (ret != 0) {
506                 talloc_free(msg);
507                 DEBUG(0,("dsdb_write_prefixes_from_schema_to_ldb: ldb_msg_add_value failed\n"));        
508                 return WERR_NOMEM;
509         }
510  
511         ret = samdb_replace( ldb, msg, msg );
512         talloc_free(msg);
513
514         if (ret != 0) {
515                 DEBUG(0,("dsdb_write_prefixes_from_schema_to_ldb: samdb_replace failed\n"));    
516                 return WERR_FOOBAR;
517         }
518  
519         return WERR_OK;
520 }
521
522 WERROR dsdb_read_prefixes_from_ldb(TALLOC_CTX *mem_ctx, struct ldb_context *ldb, uint32_t* num_prefixes, struct dsdb_schema_oid_prefix **prefixes)
523 {
524         struct prefixMapBlob *blob;
525         enum ndr_err_code ndr_err;
526         uint32_t i;
527         const struct ldb_val *prefix_val;
528         struct ldb_dn *schema_dn;
529         struct ldb_result *schema_res;
530         int ret;    
531         static const char *schema_attrs[] = {
532                 "prefixMap",
533                 NULL
534         };
535
536         schema_dn = samdb_schema_dn(ldb);
537         if (!schema_dn) {
538                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no schema dn present\n"));
539                 return WERR_FOOBAR;
540         }
541
542         ret = ldb_search(ldb, mem_ctx, &schema_res, schema_dn, LDB_SCOPE_BASE, schema_attrs, NULL);
543         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
544                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefix map present\n"));
545                 talloc_free(schema_res);
546                 return WERR_FOOBAR;
547         } else if (ret != LDB_SUCCESS) {
548                 DEBUG(0,("dsdb_read_prefixes_from_ldb: failed to search the schema head\n"));
549                 talloc_free(schema_res);
550                 return WERR_FOOBAR;
551         }
552
553         prefix_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "prefixMap");
554         if (!prefix_val) {
555                 DEBUG(0,("dsdb_read_prefixes_from_ldb: no prefixMap attribute found\n"));
556                 talloc_free(schema_res);
557                 return WERR_FOOBAR;
558         }
559
560         blob = talloc(mem_ctx, struct prefixMapBlob);
561         W_ERROR_HAVE_NO_MEMORY(blob);
562
563         ndr_err = ndr_pull_struct_blob(prefix_val, blob, 
564                                            lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), 
565                                            blob,
566                                            (ndr_pull_flags_fn_t)ndr_pull_prefixMapBlob);
567         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
568                 DEBUG(0,("dsdb_read_prefixes_from_ldb: ndr_pull_struct_blob failed\n"));
569                 talloc_free(blob);
570                 talloc_free(schema_res);
571                 return WERR_FOOBAR;
572         }
573
574         talloc_free(schema_res);
575
576         if (blob->version != PREFIX_MAP_VERSION_DSDB) {
577                 DEBUG(0,("dsdb_read_prefixes_from_ldb: blob->version incorect\n"));
578                 talloc_free(blob);
579                 return WERR_FOOBAR;
580         }
581         
582         *num_prefixes = blob->ctr.dsdb.num_mappings;
583         *prefixes = talloc_array(mem_ctx, struct dsdb_schema_oid_prefix, *num_prefixes);
584         if(!(*prefixes)) {
585                 talloc_free(blob);
586                 return WERR_NOMEM;
587         }
588         for (i=0; i < blob->ctr.dsdb.num_mappings; i++) {
589                 char *oid;
590                 (*prefixes)[i].id = blob->ctr.dsdb.mappings[i].id_prefix<<16;
591                 oid = talloc_strdup(mem_ctx, blob->ctr.dsdb.mappings[i].oid.oid);
592                 (*prefixes)[i].oid = talloc_asprintf_append(oid, "."); 
593                 (*prefixes)[i].oid_len = strlen((*prefixes)[i].oid);
594         }
595
596         talloc_free(blob);
597         return WERR_OK;
598 }
599
600 /*
601   this will be replaced with something that looks at the right part of
602   the schema once we know where unique indexing information is hidden
603  */
604 static bool dsdb_schema_unique_attribute(const char *attr)
605 {
606         const char *attrs[] = { "objectGUID", "objectSID" , NULL };
607         int i;
608         for (i=0;attrs[i];i++) {
609                 if (strcasecmp(attr, attrs[i]) == 0) {
610                         return true;
611                 }
612         }
613         return false;
614 }
615
616
617 /*
618   setup the ldb_schema_attribute field for a dsdb_attribute
619  */
620 static int dsdb_schema_setup_ldb_schema_attribute(struct ldb_context *ldb, 
621                                                   struct dsdb_attribute *attr)
622 {
623         const char *syntax = attr->syntax->ldb_syntax;
624         const struct ldb_schema_syntax *s;
625         struct ldb_schema_attribute *a;
626
627         if (!syntax) {
628                 syntax = attr->syntax->ldap_oid;
629         }
630
631         s = ldb_samba_syntax_by_lDAPDisplayName(ldb, attr->lDAPDisplayName);
632         if (s == NULL) {
633                 s = ldb_samba_syntax_by_name(ldb, syntax);
634         }
635         if (s == NULL) {
636                 s = ldb_standard_syntax_by_name(ldb, syntax);
637         }
638
639         if (s == NULL) {
640                 return LDB_ERR_OPERATIONS_ERROR;                
641         }
642
643         attr->ldb_schema_attribute = a = talloc(attr, struct ldb_schema_attribute);
644         if (attr->ldb_schema_attribute == NULL) {
645                 ldb_oom(ldb);
646                 return LDB_ERR_OPERATIONS_ERROR;
647         }
648
649         a->name = attr->lDAPDisplayName;
650         a->flags = 0;
651         a->syntax = s;
652
653         if (dsdb_schema_unique_attribute(a->name)) {
654                 a->flags |= LDB_ATTR_FLAG_UNIQUE_INDEX;
655         }
656         
657         return LDB_SUCCESS;
658 }
659
660
661 #define GET_STRING_LDB(msg, attr, mem_ctx, p, elem, strict) do { \
662         const struct ldb_val *get_string_val = ldb_msg_find_ldb_val(msg, attr); \
663         if (get_string_val == NULL) { \
664                 if (strict) {                                     \
665                         d_printf("%s: %s == NULL\n", __location__, attr); \
666                         return WERR_INVALID_PARAM;                      \
667                 } else {                                                \
668                         (p)->elem = NULL;                               \
669                 }                                                       \
670         } else {                                                        \
671                 (p)->elem = talloc_strndup(mem_ctx,                     \
672                                            (const char *)get_string_val->data, \
673                                            get_string_val->length); \
674                 if (!(p)->elem) {                                       \
675                         d_printf("%s: talloc_strndup failed for %s\n", __location__, attr); \
676                         return WERR_NOMEM;                              \
677                 }                                                       \
678         }                                                               \
679 } while (0)
680
681 #define GET_STRING_LIST_LDB(msg, attr, mem_ctx, p, elem, strict) do {   \
682         int get_string_list_counter;                                    \
683         struct ldb_message_element *get_string_list_el = ldb_msg_find_element(msg, attr); \
684         if (get_string_list_el == NULL) {                               \
685                 if (strict) {                                           \
686                         d_printf("%s: %s == NULL\n", __location__, attr); \
687                         return WERR_INVALID_PARAM;                      \
688                 } else {                                                \
689                         (p)->elem = NULL;                               \
690                         break;                                          \
691                 }                                                       \
692         }                                                               \
693         (p)->elem = talloc_array(mem_ctx, const char *, get_string_list_el->num_values + 1); \
694         for (get_string_list_counter=0;                                 \
695              get_string_list_counter < get_string_list_el->num_values;  \
696              get_string_list_counter++) {                               \
697                 (p)->elem[get_string_list_counter] = talloc_strndup((p)->elem, \
698                                                                     (const char *)get_string_list_el->values[get_string_list_counter].data, \
699                                                                     get_string_list_el->values[get_string_list_counter].length); \
700                 if (!(p)->elem[get_string_list_counter]) {              \
701                         d_printf("%s: talloc_strndup failed for %s\n", __location__, attr); \
702                         return WERR_NOMEM;                              \
703                 }                                                       \
704                 (p)->elem[get_string_list_counter+1] = NULL;            \
705         }                                                               \
706         talloc_steal(mem_ctx, (p)->elem);                               \
707 } while (0)
708
709 #define GET_BOOL_LDB(msg, attr, p, elem, strict) do { \
710         const char *str; \
711         str = samdb_result_string(msg, attr, NULL);\
712         if (str == NULL) { \
713                 if (strict) { \
714                         d_printf("%s: %s == NULL\n", __location__, attr); \
715                         return WERR_INVALID_PARAM; \
716                 } else { \
717                         (p)->elem = false; \
718                 } \
719         } else if (strcasecmp("TRUE", str) == 0) { \
720                 (p)->elem = true; \
721         } else if (strcasecmp("FALSE", str) == 0) { \
722                 (p)->elem = false; \
723         } else { \
724                 d_printf("%s: %s == %s\n", __location__, attr, str); \
725                 return WERR_INVALID_PARAM; \
726         } \
727 } while (0)
728
729 #define GET_UINT32_LDB(msg, attr, p, elem) do { \
730         (p)->elem = samdb_result_uint(msg, attr, 0);\
731 } while (0)
732
733 #define GET_UINT32_PTR_LDB(msg, attr, p, elem) do { \
734         uint64_t _v = samdb_result_uint64(msg, attr, UINT64_MAX);\
735         if (_v == UINT64_MAX) { \
736                 (p)->elem = NULL; \
737         } else if (_v > UINT32_MAX) { \
738                 d_printf("%s: %s == 0x%llX\n", __location__, \
739                          attr, (unsigned long long)_v); \
740                 return WERR_INVALID_PARAM; \
741         } else { \
742                 (p)->elem = talloc(mem_ctx, uint32_t); \
743                 if (!(p)->elem) { \
744                         d_printf("%s: talloc failed for %s\n", __location__, attr); \
745                         return WERR_NOMEM; \
746                 } \
747                 *(p)->elem = (uint32_t)_v; \
748         } \
749 } while (0)
750
751 #define GET_GUID_LDB(msg, attr, p, elem) do { \
752         (p)->elem = samdb_result_guid(msg, attr);\
753 } while (0)
754
755 #define GET_BLOB_LDB(msg, attr, mem_ctx, p, elem) do { \
756         const struct ldb_val *_val;\
757         _val = ldb_msg_find_ldb_val(msg, attr);\
758         if (_val) {\
759                 (p)->elem = *_val;\
760                 talloc_steal(mem_ctx, (p)->elem.data);\
761         } else {\
762                 ZERO_STRUCT((p)->elem);\
763         }\
764 } while (0)
765
766 WERROR dsdb_attribute_from_ldb(struct ldb_context *ldb,
767                                const struct dsdb_schema *schema,
768                                struct ldb_message *msg,
769                                TALLOC_CTX *mem_ctx,
770                                struct dsdb_attribute *attr)
771 {
772         WERROR status;
773
774         GET_STRING_LDB(msg, "cn", mem_ctx, attr, cn, false);
775         GET_STRING_LDB(msg, "lDAPDisplayName", mem_ctx, attr, lDAPDisplayName, true);
776         GET_STRING_LDB(msg, "attributeID", mem_ctx, attr, attributeID_oid, true);
777         if (schema->num_prefixes == 0) {
778                 /* set an invalid value */
779                 attr->attributeID_id = 0xFFFFFFFF;
780         } else {
781                 status = dsdb_map_oid2int(schema, attr->attributeID_oid, &attr->attributeID_id);
782                 if (!W_ERROR_IS_OK(status)) {
783                         DEBUG(0,("%s: '%s': unable to map attributeID %s: %s\n",
784                                 __location__, attr->lDAPDisplayName, attr->attributeID_oid,
785                                 win_errstr(status)));
786                         return status;
787                 }
788         }
789         GET_GUID_LDB(msg, "schemaIDGUID", attr, schemaIDGUID);
790         GET_UINT32_LDB(msg, "mAPIID", attr, mAPIID);
791
792         GET_GUID_LDB(msg, "attributeSecurityGUID", attr, attributeSecurityGUID);
793
794         GET_UINT32_LDB(msg, "searchFlags", attr, searchFlags);
795         GET_UINT32_LDB(msg, "systemFlags", attr, systemFlags);
796         GET_BOOL_LDB(msg, "isMemberOfPartialAttributeSet", attr, isMemberOfPartialAttributeSet, false);
797         GET_UINT32_LDB(msg, "linkID", attr, linkID);
798
799         GET_STRING_LDB(msg, "attributeSyntax", mem_ctx, attr, attributeSyntax_oid, true);
800         if (schema->num_prefixes == 0) {
801                 /* set an invalid value */
802                 attr->attributeSyntax_id = 0xFFFFFFFF;
803         } else {
804                 status = dsdb_map_oid2int(schema, attr->attributeSyntax_oid, &attr->attributeSyntax_id);
805                 if (!W_ERROR_IS_OK(status)) {
806                         DEBUG(0,("%s: '%s': unable to map attributeSyntax_ %s: %s\n",
807                                 __location__, attr->lDAPDisplayName, attr->attributeSyntax_oid,
808                                 win_errstr(status)));
809                         return status;
810                 }
811         }
812         GET_UINT32_LDB(msg, "oMSyntax", attr, oMSyntax);
813         GET_BLOB_LDB(msg, "oMObjectClass", mem_ctx, attr, oMObjectClass);
814
815         GET_BOOL_LDB(msg, "isSingleValued", attr, isSingleValued, true);
816         GET_UINT32_PTR_LDB(msg, "rangeLower", attr, rangeLower);
817         GET_UINT32_PTR_LDB(msg, "rangeUpper", attr, rangeUpper);
818         GET_BOOL_LDB(msg, "extendedCharsAllowed", attr, extendedCharsAllowed, false);
819
820         GET_UINT32_LDB(msg, "schemaFlagsEx", attr, schemaFlagsEx);
821         GET_BLOB_LDB(msg, "msDs-Schema-Extensions", mem_ctx, attr, msDs_Schema_Extensions);
822
823         GET_BOOL_LDB(msg, "showInAdvancedViewOnly", attr, showInAdvancedViewOnly, false);
824         GET_STRING_LDB(msg, "adminDisplayName", mem_ctx, attr, adminDisplayName, false);
825         GET_STRING_LDB(msg, "adminDescription", mem_ctx, attr, adminDescription, false);
826         GET_STRING_LDB(msg, "classDisplayName", mem_ctx, attr, classDisplayName, false);
827         GET_BOOL_LDB(msg, "isEphemeral", attr, isEphemeral, false);
828         GET_BOOL_LDB(msg, "isDefunct", attr, isDefunct, false);
829         GET_BOOL_LDB(msg, "systemOnly", attr, systemOnly, false);
830
831         attr->syntax = dsdb_syntax_for_attribute(attr);
832         if (!attr->syntax) {
833                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
834         }
835
836         if (dsdb_schema_setup_ldb_schema_attribute(ldb, attr) != LDB_SUCCESS) {
837                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
838         }
839
840         return WERR_OK;
841 }
842
843 WERROR dsdb_class_from_ldb(const struct dsdb_schema *schema,
844                            struct ldb_message *msg,
845                            TALLOC_CTX *mem_ctx,
846                            struct dsdb_class *obj)
847 {
848         WERROR status;
849
850         GET_STRING_LDB(msg, "cn", mem_ctx, obj, cn, false);
851         GET_STRING_LDB(msg, "lDAPDisplayName", mem_ctx, obj, lDAPDisplayName, true);
852         GET_STRING_LDB(msg, "governsID", mem_ctx, obj, governsID_oid, true);
853         if (schema->num_prefixes == 0) {
854                 /* set an invalid value */
855                 obj->governsID_id = 0xFFFFFFFF;
856         } else {
857                 status = dsdb_map_oid2int(schema, obj->governsID_oid, &obj->governsID_id);
858                 if (!W_ERROR_IS_OK(status)) {
859                         DEBUG(0,("%s: '%s': unable to map governsID %s: %s\n",
860                                 __location__, obj->lDAPDisplayName, obj->governsID_oid,
861                                 win_errstr(status)));
862                         return status;
863                 }
864         }
865         GET_GUID_LDB(msg, "schemaIDGUID", obj, schemaIDGUID);
866
867         GET_UINT32_LDB(msg, "objectClassCategory", obj, objectClassCategory);
868         GET_STRING_LDB(msg, "rDNAttID", mem_ctx, obj, rDNAttID, false);
869         GET_STRING_LDB(msg, "defaultObjectCategory", mem_ctx, obj, defaultObjectCategory, true);
870  
871         GET_STRING_LDB(msg, "subClassOf", mem_ctx, obj, subClassOf, true);
872
873         GET_STRING_LIST_LDB(msg, "systemAuxiliaryClass", mem_ctx, obj, systemAuxiliaryClass, false);
874         GET_STRING_LIST_LDB(msg, "auxiliaryClass", mem_ctx, obj, auxiliaryClass, false);
875
876         GET_STRING_LIST_LDB(msg, "systemMustContain", mem_ctx, obj, systemMustContain, false);
877         GET_STRING_LIST_LDB(msg, "systemMayContain", mem_ctx, obj, systemMayContain, false);
878         GET_STRING_LIST_LDB(msg, "mustContain", mem_ctx, obj, mustContain, false);
879         GET_STRING_LIST_LDB(msg, "mayContain", mem_ctx, obj, mayContain, false);
880
881         GET_STRING_LIST_LDB(msg, "systemPossSuperiors", mem_ctx, obj, systemPossSuperiors, false);
882         GET_STRING_LIST_LDB(msg, "possSuperiors", mem_ctx, obj, possSuperiors, false);
883
884         GET_STRING_LDB(msg, "defaultSecurityDescriptor", mem_ctx, obj, defaultSecurityDescriptor, false);
885
886         GET_UINT32_LDB(msg, "schemaFlagsEx", obj, schemaFlagsEx);
887         GET_BLOB_LDB(msg, "msDs-Schema-Extensions", mem_ctx, obj, msDs_Schema_Extensions);
888
889         GET_BOOL_LDB(msg, "showInAdvancedViewOnly", obj, showInAdvancedViewOnly, false);
890         GET_STRING_LDB(msg, "adminDisplayName", mem_ctx, obj, adminDisplayName, false);
891         GET_STRING_LDB(msg, "adminDescription", mem_ctx, obj, adminDescription, false);
892         GET_STRING_LDB(msg, "classDisplayName", mem_ctx, obj, classDisplayName, false);
893         GET_BOOL_LDB(msg, "defaultHidingValue", obj, defaultHidingValue, false);
894         GET_BOOL_LDB(msg, "isDefunct", obj, isDefunct, false);
895         GET_BOOL_LDB(msg, "systemOnly", obj, systemOnly, false);
896
897         return WERR_OK;
898 }
899
900 #define dsdb_oom(error_string, mem_ctx) *error_string = talloc_asprintf(mem_ctx, "dsdb out of memory at %s:%d\n", __FILE__, __LINE__)
901
902 /* 
903  Create a DSDB schema from the ldb results provided.  This is called
904  directly when the schema is provisioned from an on-disk LDIF file, or
905  from dsdb_schema_from_schema_dn below
906 */
907
908 int dsdb_schema_from_ldb_results(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
909                                  struct smb_iconv_convenience *iconv_convenience, 
910                                  struct ldb_result *schema_res,
911                                  struct ldb_result *attrs_res, struct ldb_result *objectclass_res, 
912                                  struct dsdb_schema **schema_out,
913                                  char **error_string)
914 {
915         WERROR status;
916         uint32_t i;
917         const struct ldb_val *prefix_val;
918         const struct ldb_val *info_val;
919         struct ldb_val info_val_default;
920         struct dsdb_schema *schema;
921
922         schema = dsdb_new_schema(mem_ctx, iconv_convenience);
923         if (!schema) {
924                 dsdb_oom(error_string, mem_ctx);
925                 return LDB_ERR_OPERATIONS_ERROR;
926         }
927
928         prefix_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "prefixMap");
929         if (!prefix_val) {
930                 *error_string = talloc_asprintf(mem_ctx, 
931                                                 "schema_fsmo_init: no prefixMap attribute found");
932                 return LDB_ERR_CONSTRAINT_VIOLATION;
933         }
934         info_val = ldb_msg_find_ldb_val(schema_res->msgs[0], "schemaInfo");
935         if (!info_val) {
936                 info_val_default = strhex_to_data_blob(mem_ctx, "FF0000000000000000000000000000000000000000");
937                 if (!info_val_default.data) {
938                         dsdb_oom(error_string, mem_ctx);
939                         return LDB_ERR_OPERATIONS_ERROR;
940                 }
941                 info_val = &info_val_default;
942         }
943
944         status = dsdb_load_oid_mappings_ldb(schema, prefix_val, info_val);
945         if (!W_ERROR_IS_OK(status)) {
946                 *error_string = talloc_asprintf(mem_ctx, 
947                               "schema_fsmo_init: failed to load oid mappings: %s",
948                               win_errstr(status));
949                 return LDB_ERR_CONSTRAINT_VIOLATION;
950         }
951
952         for (i=0; i < attrs_res->count; i++) {
953                 struct dsdb_attribute *sa;
954
955                 sa = talloc_zero(schema, struct dsdb_attribute);
956                 if (!sa) {
957                         dsdb_oom(error_string, mem_ctx);
958                         return LDB_ERR_OPERATIONS_ERROR;
959                 }
960
961                 status = dsdb_attribute_from_ldb(ldb, schema, attrs_res->msgs[i], sa, sa);
962                 if (!W_ERROR_IS_OK(status)) {
963                         *error_string = talloc_asprintf(mem_ctx, 
964                                       "schema_fsmo_init: failed to load attribute definition: %s:%s",
965                                       ldb_dn_get_linearized(attrs_res->msgs[i]->dn),
966                                       win_errstr(status));
967                         return LDB_ERR_CONSTRAINT_VIOLATION;
968                 }
969
970                 DLIST_ADD(schema->attributes, sa);
971         }
972
973         for (i=0; i < objectclass_res->count; i++) {
974                 struct dsdb_class *sc;
975
976                 sc = talloc_zero(schema, struct dsdb_class);
977                 if (!sc) {
978                         dsdb_oom(error_string, mem_ctx);
979                         return LDB_ERR_OPERATIONS_ERROR;
980                 }
981
982                 status = dsdb_class_from_ldb(schema, objectclass_res->msgs[i], sc, sc);
983                 if (!W_ERROR_IS_OK(status)) {
984                         *error_string = talloc_asprintf(mem_ctx, 
985                                       "schema_fsmo_init: failed to load class definition: %s:%s",
986                                       ldb_dn_get_linearized(objectclass_res->msgs[i]->dn),
987                                       win_errstr(status));
988                         return LDB_ERR_CONSTRAINT_VIOLATION;
989                 }
990
991                 DLIST_ADD(schema->classes, sc);
992         }
993
994         schema->fsmo.master_dn = ldb_msg_find_attr_as_dn(ldb, schema, schema_res->msgs[0], "fSMORoleOwner");
995         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), schema->fsmo.master_dn) == 0) {
996                 schema->fsmo.we_are_master = true;
997         } else {
998                 schema->fsmo.we_are_master = false;
999         }
1000
1001         DEBUG(5, ("schema_fsmo_init: we are master: %s\n",
1002                   (schema->fsmo.we_are_master?"yes":"no")));
1003
1004         *schema_out = schema;
1005         return LDB_SUCCESS;
1006 }
1007
1008 /*
1009   Given an LDB, and the DN, return a populated schema
1010 */
1011
1012 int dsdb_schema_from_schema_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
1013                                struct smb_iconv_convenience *iconv_convenience, 
1014                                struct ldb_dn *schema_dn,
1015                                struct dsdb_schema **schema,
1016                                char **error_string_out) 
1017 {
1018         TALLOC_CTX *tmp_ctx;
1019         char *error_string;
1020         int ret;
1021
1022         struct ldb_result *schema_res;
1023         struct ldb_result *a_res;
1024         struct ldb_result *c_res;
1025         static const char *schema_attrs[] = {
1026                 "prefixMap",
1027                 "schemaInfo",
1028                 "fSMORoleOwner",
1029                 NULL
1030         };
1031         unsigned flags;
1032
1033         tmp_ctx = talloc_new(mem_ctx);
1034         if (!tmp_ctx) {
1035                 dsdb_oom(error_string_out, mem_ctx);
1036                 return LDB_ERR_OPERATIONS_ERROR;
1037         }
1038
1039         /* we don't want to trace the schema load */
1040         flags = ldb_get_flags(ldb);
1041         ldb_set_flags(ldb, flags & ~LDB_FLG_ENABLE_TRACING);
1042
1043         /*
1044          * setup the prefix mappings and schema info
1045          */
1046         ret = ldb_search(ldb, tmp_ctx, &schema_res,
1047                          schema_dn, LDB_SCOPE_BASE, schema_attrs, NULL);
1048         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1049                 goto failed;
1050         } else if (ret != LDB_SUCCESS) {
1051                 *error_string_out = talloc_asprintf(mem_ctx, 
1052                                        "dsdb_schema: failed to search the schema head: %s",
1053                                        ldb_errstring(ldb));
1054                 goto failed;
1055         }
1056         if (schema_res->count != 1) {
1057                 *error_string_out = talloc_asprintf(mem_ctx, 
1058                               "dsdb_schema: [%u] schema heads found on a base search",
1059                               schema_res->count);
1060                 goto failed;
1061         }
1062
1063         /*
1064          * load the attribute definitions
1065          */
1066         ret = ldb_search(ldb, tmp_ctx, &a_res,
1067                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
1068                          "(objectClass=attributeSchema)");
1069         if (ret != LDB_SUCCESS) {
1070                 *error_string_out = talloc_asprintf(mem_ctx, 
1071                                        "dsdb_schema: failed to search attributeSchema objects: %s",
1072                                        ldb_errstring(ldb));
1073                 goto failed;
1074         }
1075
1076         /*
1077          * load the objectClass definitions
1078          */
1079         ret = ldb_search(ldb, tmp_ctx, &c_res,
1080                          schema_dn, LDB_SCOPE_ONELEVEL, NULL,
1081                          "(objectClass=classSchema)");
1082         if (ret != LDB_SUCCESS) {
1083                 *error_string_out = talloc_asprintf(mem_ctx, 
1084                                        "dsdb_schema: failed to search attributeSchema objects: %s",
1085                                        ldb_errstring(ldb));
1086                 goto failed;
1087         }
1088
1089         ret = dsdb_schema_from_ldb_results(tmp_ctx, ldb,
1090                                            lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
1091                                            schema_res, a_res, c_res, schema, &error_string);
1092         if (ret != LDB_SUCCESS) {
1093                 *error_string_out = talloc_asprintf(mem_ctx, 
1094                                                     "dsdb_schema load failed: %s",
1095                                                     error_string);
1096                 goto failed;
1097         }
1098         talloc_steal(mem_ctx, *schema);
1099         talloc_free(tmp_ctx);
1100
1101         if (flags & LDB_FLG_ENABLE_TRACING) {
1102                 flags = ldb_get_flags(ldb);
1103                 ldb_set_flags(ldb, flags | LDB_FLG_ENABLE_TRACING);
1104         }
1105
1106         return LDB_SUCCESS;
1107
1108 failed:
1109         if (flags & LDB_FLG_ENABLE_TRACING) {
1110                 flags = ldb_get_flags(ldb);
1111                 ldb_set_flags(ldb, flags | LDB_FLG_ENABLE_TRACING);
1112         }
1113         talloc_free(tmp_ctx);
1114         return ret;
1115 }       
1116
1117
1118 static const struct {
1119         const char *name;
1120         const char *oid;
1121 } name_mappings[] = {
1122         { "cn",                                 "2.5.4.3" },
1123         { "name",                               "1.2.840.113556.1.4.1" },
1124         { "lDAPDisplayName",                    "1.2.840.113556.1.2.460" },
1125         { "attributeID",                        "1.2.840.113556.1.2.30" },
1126         { "schemaIDGUID",                       "1.2.840.113556.1.4.148" },
1127         { "mAPIID",                             "1.2.840.113556.1.2.49" },
1128         { "attributeSecurityGUID",              "1.2.840.113556.1.4.149" },
1129         { "searchFlags",                        "1.2.840.113556.1.2.334" },
1130         { "systemFlags",                        "1.2.840.113556.1.4.375" },
1131         { "isMemberOfPartialAttributeSet",      "1.2.840.113556.1.4.639" },
1132         { "linkID",                             "1.2.840.113556.1.2.50" },
1133         { "attributeSyntax",                    "1.2.840.113556.1.2.32" },
1134         { "oMSyntax",                           "1.2.840.113556.1.2.231" },
1135         { "oMObjectClass",                      "1.2.840.113556.1.2.218" },
1136         { "isSingleValued",                     "1.2.840.113556.1.2.33" },
1137         { "rangeLower",                         "1.2.840.113556.1.2.34" },
1138         { "rangeUpper",                         "1.2.840.113556.1.2.35" },
1139         { "extendedCharsAllowed",               "1.2.840.113556.1.2.380" },
1140         { "schemaFlagsEx",                      "1.2.840.113556.1.4.120" },
1141         { "msDs-Schema-Extensions",             "1.2.840.113556.1.4.1440" },
1142         { "showInAdvancedViewOnly",             "1.2.840.113556.1.2.169" },
1143         { "adminDisplayName",                   "1.2.840.113556.1.2.194" },
1144         { "adminDescription",                   "1.2.840.113556.1.2.226" },
1145         { "classDisplayName",                   "1.2.840.113556.1.4.610" },
1146         { "isEphemeral",                        "1.2.840.113556.1.4.1212" },
1147         { "isDefunct",                          "1.2.840.113556.1.4.661" },
1148         { "systemOnly",                         "1.2.840.113556.1.4.170" },
1149         { "governsID",                          "1.2.840.113556.1.2.22" },
1150         { "objectClassCategory",                "1.2.840.113556.1.2.370" },
1151         { "rDNAttID",                           "1.2.840.113556.1.2.26" },
1152         { "defaultObjectCategory",              "1.2.840.113556.1.4.783" },
1153         { "subClassOf",                         "1.2.840.113556.1.2.21" },
1154         { "systemAuxiliaryClass",               "1.2.840.113556.1.4.198" },
1155         { "systemPossSuperiors",                "1.2.840.113556.1.4.195" },
1156         { "systemMustContain",                  "1.2.840.113556.1.4.197" },
1157         { "systemMayContain",                   "1.2.840.113556.1.4.196" },
1158         { "auxiliaryClass",                     "1.2.840.113556.1.2.351" },
1159         { "possSuperiors",                      "1.2.840.113556.1.2.8" },
1160         { "mustContain",                        "1.2.840.113556.1.2.24" },
1161         { "mayContain",                         "1.2.840.113556.1.2.25" },
1162         { "defaultSecurityDescriptor",          "1.2.840.113556.1.4.224" },
1163         { "defaultHidingValue",                 "1.2.840.113556.1.4.518" },
1164 };
1165
1166 static struct drsuapi_DsReplicaAttribute *dsdb_find_object_attr_name(struct dsdb_schema *schema,
1167                                                                      struct drsuapi_DsReplicaObject *obj,
1168                                                                      const char *name,
1169                                                                      uint32_t *idx)
1170 {
1171         WERROR status;
1172         uint32_t i, id;
1173         const char *oid = NULL;
1174
1175         for(i=0; i < ARRAY_SIZE(name_mappings); i++) {
1176                 if (strcmp(name_mappings[i].name, name) != 0) continue;
1177
1178                 oid = name_mappings[i].oid;
1179                 break;
1180         }
1181
1182         if (!oid) {
1183                 return NULL;
1184         }
1185
1186         status = dsdb_map_oid2int(schema, oid, &id);
1187         if (!W_ERROR_IS_OK(status)) {
1188                 return NULL;
1189         }
1190
1191         for (i=0; i < obj->attribute_ctr.num_attributes; i++) {
1192                 if (obj->attribute_ctr.attributes[i].attid != id) continue;
1193
1194                 if (idx) *idx = i;
1195                 return &obj->attribute_ctr.attributes[i];
1196         }
1197
1198         return NULL;
1199 }
1200
1201 #define GET_STRING_DS(s, r, attr, mem_ctx, p, elem, strict) do { \
1202         struct drsuapi_DsReplicaAttribute *_a; \
1203         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1204         if (strict && !_a) { \
1205                 d_printf("%s: %s == NULL\n", __location__, attr); \
1206                 return WERR_INVALID_PARAM; \
1207         } \
1208         if (strict && _a->value_ctr.num_values != 1) { \
1209                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1210                         _a->value_ctr.num_values); \
1211                 return WERR_INVALID_PARAM; \
1212         } \
1213         if (_a && _a->value_ctr.num_values >= 1) { \
1214                 size_t _ret; \
1215                 if (!convert_string_talloc_convenience(mem_ctx, s->iconv_convenience, CH_UTF16, CH_UNIX, \
1216                                              _a->value_ctr.values[0].blob->data, \
1217                                              _a->value_ctr.values[0].blob->length, \
1218                                              (void **)discard_const(&(p)->elem), &_ret, false)) { \
1219                         DEBUG(0,("%s: invalid data!\n", attr)); \
1220                         dump_data(0, \
1221                                      _a->value_ctr.values[0].blob->data, \
1222                                      _a->value_ctr.values[0].blob->length); \
1223                         return WERR_FOOBAR; \
1224                 } \
1225         } else { \
1226                 (p)->elem = NULL; \
1227         } \
1228 } while (0)
1229
1230 #define GET_UINT32_LIST_DS(s, r, attr, mem_ctx, p, elem) do { \
1231         int list_counter;                                       \
1232         struct drsuapi_DsReplicaAttribute *_a; \
1233         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1234         (p)->elem = _a ? talloc_array(mem_ctx, uint32_t, _a->value_ctr.num_values + 1) : NULL; \
1235         for (list_counter=0;                                    \
1236              _a && list_counter < _a->value_ctr.num_values;     \
1237              list_counter++) {                          \
1238                 if (_a->value_ctr.values[list_counter].blob->length != 4) { \
1239                         return WERR_INVALID_PARAM;                      \
1240                 }                                                       \
1241                 (p)->elem[list_counter] = IVAL(_a->value_ctr.values[list_counter].blob->data, 0); \
1242         }                                                               \
1243         if (_a) (p)->elem[list_counter] = 0;                            \
1244 } while (0)
1245
1246 #define GET_DN_DS(s, r, attr, mem_ctx, p, elem, strict) do { \
1247         struct drsuapi_DsReplicaAttribute *_a; \
1248         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1249         if (strict && !_a) { \
1250                 d_printf("%s: %s == NULL\n", __location__, attr); \
1251                 return WERR_INVALID_PARAM; \
1252         } \
1253         if (strict && _a->value_ctr.num_values != 1) { \
1254                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1255                         _a->value_ctr.num_values); \
1256                 return WERR_INVALID_PARAM; \
1257         } \
1258         if (strict && !_a->value_ctr.values[0].blob) { \
1259                 d_printf("%s: %s data == NULL\n", __location__, attr); \
1260                 return WERR_INVALID_PARAM; \
1261         } \
1262         if (_a && _a->value_ctr.num_values >= 1 \
1263             && _a->value_ctr.values[0].blob) { \
1264                 struct drsuapi_DsReplicaObjectIdentifier3 _id3; \
1265                 enum ndr_err_code _ndr_err; \
1266                 _ndr_err = ndr_pull_struct_blob_all(_a->value_ctr.values[0].blob, \
1267                                                       mem_ctx, s->iconv_convenience, &_id3,\
1268                                                       (ndr_pull_flags_fn_t)ndr_pull_drsuapi_DsReplicaObjectIdentifier3);\
1269                 if (!NDR_ERR_CODE_IS_SUCCESS(_ndr_err)) { \
1270                         NTSTATUS _nt_status = ndr_map_error2ntstatus(_ndr_err); \
1271                         return ntstatus_to_werror(_nt_status); \
1272                 } \
1273                 (p)->elem = _id3.dn; \
1274         } else { \
1275                 (p)->elem = NULL; \
1276         } \
1277 } while (0)
1278
1279 #define GET_BOOL_DS(s, r, attr, p, elem, strict) do { \
1280         struct drsuapi_DsReplicaAttribute *_a; \
1281         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1282         if (strict && !_a) { \
1283                 d_printf("%s: %s == NULL\n", __location__, attr); \
1284                 return WERR_INVALID_PARAM; \
1285         } \
1286         if (strict && _a->value_ctr.num_values != 1) { \
1287                 d_printf("%s: %s num_values == %u\n", __location__, attr, \
1288                          (unsigned int)_a->value_ctr.num_values);       \
1289                 return WERR_INVALID_PARAM; \
1290         } \
1291         if (strict && !_a->value_ctr.values[0].blob) { \
1292                 d_printf("%s: %s data == NULL\n", __location__, attr); \
1293                 return WERR_INVALID_PARAM; \
1294         } \
1295         if (strict && _a->value_ctr.values[0].blob->length != 4) { \
1296                 d_printf("%s: %s length == %u\n", __location__, attr, \
1297                          (unsigned int)_a->value_ctr.values[0].blob->length); \
1298                 return WERR_INVALID_PARAM; \
1299         } \
1300         if (_a && _a->value_ctr.num_values >= 1 \
1301             && _a->value_ctr.values[0].blob \
1302             && _a->value_ctr.values[0].blob->length == 4) { \
1303                 (p)->elem = (IVAL(_a->value_ctr.values[0].blob->data,0)?true:false);\
1304         } else { \
1305                 (p)->elem = false; \
1306         } \
1307 } while (0)
1308
1309 #define GET_UINT32_DS(s, r, attr, p, elem) do { \
1310         struct drsuapi_DsReplicaAttribute *_a; \
1311         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1312         if (_a && _a->value_ctr.num_values >= 1 \
1313             && _a->value_ctr.values[0].blob \
1314             && _a->value_ctr.values[0].blob->length == 4) { \
1315                 (p)->elem = IVAL(_a->value_ctr.values[0].blob->data,0);\
1316         } else { \
1317                 (p)->elem = 0; \
1318         } \
1319 } while (0)
1320
1321 #define GET_UINT32_PTR_DS(s, r, attr, p, elem) do { \
1322         struct drsuapi_DsReplicaAttribute *_a; \
1323         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1324         if (_a && _a->value_ctr.num_values >= 1 \
1325             && _a->value_ctr.values[0].blob \
1326             && _a->value_ctr.values[0].blob->length == 4) { \
1327                 (p)->elem = talloc(mem_ctx, uint32_t); \
1328                 if (!(p)->elem) { \
1329                         d_printf("%s: talloc failed for %s\n", __location__, attr); \
1330                         return WERR_NOMEM; \
1331                 } \
1332                 *(p)->elem = IVAL(_a->value_ctr.values[0].blob->data,0);\
1333         } else { \
1334                 (p)->elem = NULL; \
1335         } \
1336 } while (0)
1337
1338 #define GET_GUID_DS(s, r, attr, mem_ctx, p, elem) do { \
1339         struct drsuapi_DsReplicaAttribute *_a; \
1340         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1341         if (_a && _a->value_ctr.num_values >= 1 \
1342             && _a->value_ctr.values[0].blob \
1343             && _a->value_ctr.values[0].blob->length == 16) { \
1344                 enum ndr_err_code _ndr_err; \
1345                 _ndr_err = ndr_pull_struct_blob_all(_a->value_ctr.values[0].blob, \
1346                                                       mem_ctx, s->iconv_convenience, &(p)->elem, \
1347                                                       (ndr_pull_flags_fn_t)ndr_pull_GUID); \
1348                 if (!NDR_ERR_CODE_IS_SUCCESS(_ndr_err)) { \
1349                         NTSTATUS _nt_status = ndr_map_error2ntstatus(_ndr_err); \
1350                         return ntstatus_to_werror(_nt_status); \
1351                 } \
1352         } else { \
1353                 ZERO_STRUCT((p)->elem);\
1354         } \
1355 } while (0)
1356
1357 #define GET_BLOB_DS(s, r, attr, mem_ctx, p, elem) do { \
1358         struct drsuapi_DsReplicaAttribute *_a; \
1359         _a = dsdb_find_object_attr_name(s, r, attr, NULL); \
1360         if (_a && _a->value_ctr.num_values >= 1 \
1361             && _a->value_ctr.values[0].blob) { \
1362                 (p)->elem = *_a->value_ctr.values[0].blob;\
1363                 talloc_steal(mem_ctx, (p)->elem.data); \
1364         } else { \
1365                 ZERO_STRUCT((p)->elem);\
1366         }\
1367 } while (0)
1368
1369 WERROR dsdb_attribute_from_drsuapi(struct ldb_context *ldb,
1370                                    struct dsdb_schema *schema,
1371                                    struct drsuapi_DsReplicaObject *r,
1372                                    TALLOC_CTX *mem_ctx,
1373                                    struct dsdb_attribute *attr)
1374 {
1375         WERROR status;
1376
1377         GET_STRING_DS(schema, r, "name", mem_ctx, attr, cn, true);
1378         GET_STRING_DS(schema, r, "lDAPDisplayName", mem_ctx, attr, lDAPDisplayName, true);
1379         GET_UINT32_DS(schema, r, "attributeID", attr, attributeID_id);
1380         status = dsdb_map_int2oid(schema, attr->attributeID_id, mem_ctx, &attr->attributeID_oid);
1381         if (!W_ERROR_IS_OK(status)) {
1382                 DEBUG(0,("%s: '%s': unable to map attributeID 0x%08X: %s\n",
1383                         __location__, attr->lDAPDisplayName, attr->attributeID_id,
1384                         win_errstr(status)));
1385                 return status;
1386         }
1387         GET_GUID_DS(schema, r, "schemaIDGUID", mem_ctx, attr, schemaIDGUID);
1388         GET_UINT32_DS(schema, r, "mAPIID", attr, mAPIID);
1389
1390         GET_GUID_DS(schema, r, "attributeSecurityGUID", mem_ctx, attr, attributeSecurityGUID);
1391
1392         GET_UINT32_DS(schema, r, "searchFlags", attr, searchFlags);
1393         GET_UINT32_DS(schema, r, "systemFlags", attr, systemFlags);
1394         GET_BOOL_DS(schema, r, "isMemberOfPartialAttributeSet", attr, isMemberOfPartialAttributeSet, false);
1395         GET_UINT32_DS(schema, r, "linkID", attr, linkID);
1396
1397         GET_UINT32_DS(schema, r, "attributeSyntax", attr, attributeSyntax_id);
1398         status = dsdb_map_int2oid(schema, attr->attributeSyntax_id, mem_ctx, &attr->attributeSyntax_oid);
1399         if (!W_ERROR_IS_OK(status)) {
1400                 DEBUG(0,("%s: '%s': unable to map attributeSyntax 0x%08X: %s\n",
1401                         __location__, attr->lDAPDisplayName, attr->attributeSyntax_id,
1402                         win_errstr(status)));
1403                 return status;
1404         }
1405         GET_UINT32_DS(schema, r, "oMSyntax", attr, oMSyntax);
1406         GET_BLOB_DS(schema, r, "oMObjectClass", mem_ctx, attr, oMObjectClass);
1407
1408         GET_BOOL_DS(schema, r, "isSingleValued", attr, isSingleValued, true);
1409         GET_UINT32_PTR_DS(schema, r, "rangeLower", attr, rangeLower);
1410         GET_UINT32_PTR_DS(schema, r, "rangeUpper", attr, rangeUpper);
1411         GET_BOOL_DS(schema, r, "extendedCharsAllowed", attr, extendedCharsAllowed, false);
1412
1413         GET_UINT32_DS(schema, r, "schemaFlagsEx", attr, schemaFlagsEx);
1414         GET_BLOB_DS(schema, r, "msDs-Schema-Extensions", mem_ctx, attr, msDs_Schema_Extensions);
1415
1416         GET_BOOL_DS(schema, r, "showInAdvancedViewOnly", attr, showInAdvancedViewOnly, false);
1417         GET_STRING_DS(schema, r, "adminDisplayName", mem_ctx, attr, adminDisplayName, false);
1418         GET_STRING_DS(schema, r, "adminDescription", mem_ctx, attr, adminDescription, false);
1419         GET_STRING_DS(schema, r, "classDisplayName", mem_ctx, attr, classDisplayName, false);
1420         GET_BOOL_DS(schema, r, "isEphemeral", attr, isEphemeral, false);
1421         GET_BOOL_DS(schema, r, "isDefunct", attr, isDefunct, false);
1422         GET_BOOL_DS(schema, r, "systemOnly", attr, systemOnly, false);
1423
1424         attr->syntax = dsdb_syntax_for_attribute(attr);
1425         if (!attr->syntax) {
1426                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
1427         }
1428
1429         if (dsdb_schema_setup_ldb_schema_attribute(ldb, attr) != LDB_SUCCESS) {
1430                 return WERR_DS_ATT_SCHEMA_REQ_SYNTAX;
1431         }
1432
1433         return WERR_OK;
1434 }
1435
1436 WERROR dsdb_class_from_drsuapi(struct dsdb_schema *schema,
1437                                struct drsuapi_DsReplicaObject *r,
1438                                TALLOC_CTX *mem_ctx,
1439                                struct dsdb_class *obj)
1440 {
1441         WERROR status;
1442
1443         GET_STRING_DS(schema, r, "name", mem_ctx, obj, cn, true);
1444         GET_STRING_DS(schema, r, "lDAPDisplayName", mem_ctx, obj, lDAPDisplayName, true);
1445         GET_UINT32_DS(schema, r, "governsID", obj, governsID_id);
1446         status = dsdb_map_int2oid(schema, obj->governsID_id, mem_ctx, &obj->governsID_oid);
1447         if (!W_ERROR_IS_OK(status)) {
1448                 DEBUG(0,("%s: '%s': unable to map governsID 0x%08X: %s\n",
1449                         __location__, obj->lDAPDisplayName, obj->governsID_id,
1450                         win_errstr(status)));
1451                 return status;
1452         }
1453         GET_GUID_DS(schema, r, "schemaIDGUID", mem_ctx, obj, schemaIDGUID);
1454
1455         GET_UINT32_DS(schema, r, "objectClassCategory", obj, objectClassCategory);
1456         GET_STRING_DS(schema, r, "rDNAttID", mem_ctx, obj, rDNAttID, false);
1457         GET_DN_DS(schema, r, "defaultObjectCategory", mem_ctx, obj, defaultObjectCategory, true);
1458
1459         GET_UINT32_DS(schema, r, "subClassOf", obj, subClassOf_id);
1460
1461         GET_UINT32_LIST_DS(schema, r, "systemAuxiliaryClass", mem_ctx, obj, systemAuxiliaryClass_ids);
1462         GET_UINT32_LIST_DS(schema, r, "auxiliaryClass", mem_ctx, obj, auxiliaryClass_ids);
1463
1464         GET_UINT32_LIST_DS(schema, r, "systemMustContain", mem_ctx, obj, systemMustContain_ids);
1465         GET_UINT32_LIST_DS(schema, r, "systemMayContain", mem_ctx, obj, systemMayContain_ids);
1466         GET_UINT32_LIST_DS(schema, r, "mustContain", mem_ctx, obj, mustContain_ids);
1467         GET_UINT32_LIST_DS(schema, r, "mayContain", mem_ctx, obj, mayContain_ids);
1468
1469         GET_UINT32_LIST_DS(schema, r, "systemPossSuperiors", mem_ctx, obj, systemPossSuperiors_ids);
1470         GET_UINT32_LIST_DS(schema, r, "possSuperiors", mem_ctx, obj, possSuperiors_ids);
1471
1472         GET_STRING_DS(schema, r, "defaultSecurityDescriptor", mem_ctx, obj, defaultSecurityDescriptor, false);
1473
1474         GET_UINT32_DS(schema, r, "schemaFlagsEx", obj, schemaFlagsEx);
1475         GET_BLOB_DS(schema, r, "msDs-Schema-Extensions", mem_ctx, obj, msDs_Schema_Extensions);
1476
1477         GET_BOOL_DS(schema, r, "showInAdvancedViewOnly", obj, showInAdvancedViewOnly, false);
1478         GET_STRING_DS(schema, r, "adminDisplayName", mem_ctx, obj, adminDisplayName, false);
1479         GET_STRING_DS(schema, r, "adminDescription", mem_ctx, obj, adminDescription, false);
1480         GET_STRING_DS(schema, r, "classDisplayName", mem_ctx, obj, classDisplayName, false);
1481         GET_BOOL_DS(schema, r, "defaultHidingValue", obj, defaultHidingValue, false);
1482         GET_BOOL_DS(schema, r, "isDefunct", obj, isDefunct, false);
1483         GET_BOOL_DS(schema, r, "systemOnly", obj, systemOnly, false);
1484
1485         return WERR_OK;
1486 }
1487