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