dsdb-repl: Allow the name attribute (and name-based schema lookups) to be skipped...
[obnox/samba/samba-obnox.git] / source4 / dsdb / repl / replicated_objects.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    Helper functions for applying replicated objects
4    
5    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
6     
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19    
20 */
21
22 #include "includes.h"
23 #include "dsdb/samdb/samdb.h"
24 #include <ldb_errors.h>
25 #include "../lib/util/dlinklist.h"
26 #include "librpc/gen_ndr/ndr_misc.h"
27 #include "librpc/gen_ndr/ndr_drsuapi.h"
28 #include "librpc/gen_ndr/ndr_drsblobs.h"
29 #include "../lib/crypto/crypto.h"
30 #include "../libcli/drsuapi/drsuapi.h"
31 #include "libcli/auth/libcli_auth.h"
32 #include "param/param.h"
33
34 /**
35  * Multi-pass working schema creation
36  * Function will:
37  *  - shallow copy initial schema supplied
38  *  - create a working schema in multiple passes
39  *    until all objects are resolved
40  * Working schema is a schema with Attributes, Classes
41  * and indexes, but w/o subClassOf, possibleSupperiors etc.
42  * It is to be used just us cache for converting attribute values.
43  */
44 WERROR dsdb_repl_make_working_schema(struct ldb_context *ldb,
45                                      const struct dsdb_schema *initial_schema,
46                                      const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr,
47                                      uint32_t object_count,
48                                      const struct drsuapi_DsReplicaObjectListItemEx *first_object,
49                                      const DATA_BLOB *gensec_skey,
50                                      TALLOC_CTX *mem_ctx,
51                                      struct dsdb_schema **_schema_out)
52 {
53         struct schema_list {
54                 struct schema_list *next, *prev;
55                 const struct drsuapi_DsReplicaObjectListItemEx *obj;
56         };
57
58         WERROR werr;
59         struct dsdb_schema_prefixmap *pfm_remote;
60         struct schema_list *schema_list = NULL, *schema_list_item, *schema_list_next_item;
61         struct dsdb_schema *working_schema;
62         const struct drsuapi_DsReplicaObjectListItemEx *cur;
63         int ret, pass_no;
64         uint32_t ignore_attids[] = {
65                         DRSUAPI_ATTID_auxiliaryClass,
66                         DRSUAPI_ATTID_mayContain,
67                         DRSUAPI_ATTID_mustContain,
68                         DRSUAPI_ATTID_possSuperiors,
69                         DRSUAPI_ATTID_systemPossSuperiors,
70                         DRSUAPI_ATTID_INVALID
71         };
72
73         /* make a copy of the iniatial_scheam so we don't mess with it */
74         working_schema = dsdb_schema_copy_shallow(mem_ctx, ldb, initial_schema);
75         if (!working_schema) {
76                 DEBUG(0,(__location__ ": schema copy failed!\n"));
77                 return WERR_NOMEM;
78         }
79
80         /* we are going to need remote prefixMap for decoding */
81         werr = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
82                                                 mem_ctx, &pfm_remote, NULL);
83         if (!W_ERROR_IS_OK(werr)) {
84                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
85                          win_errstr(werr)));
86                 return werr;
87         }
88
89         /* create a list of objects yet to be converted */
90         for (cur = first_object; cur; cur = cur->next_object) {
91                 schema_list_item = talloc(mem_ctx, struct schema_list);
92                 schema_list_item->obj = cur;
93                 DLIST_ADD_END(schema_list, schema_list_item, struct schema_list);
94         }
95
96         /* resolve objects until all are resolved and in local schema */
97         pass_no = 1;
98
99         while (schema_list) {
100                 uint32_t converted_obj_count = 0;
101                 uint32_t failed_obj_count = 0;
102                 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
103                 W_ERROR_HAVE_NO_MEMORY(tmp_ctx);
104
105                 for (schema_list_item = schema_list; schema_list_item; schema_list_item=schema_list_next_item) {
106                         struct dsdb_extended_replicated_object object;
107
108                         cur = schema_list_item->obj;
109
110                         /* Save the next item, now we have saved out
111                          * the current one, so we can DLIST_REMOVE it
112                          * safely */
113                         schema_list_next_item = schema_list_item->next;
114
115                         /*
116                          * Convert the objects into LDB messages using the
117                          * schema we have so far. It's ok if we fail to convert
118                          * an object. We should convert more objects on next pass.
119                          */
120                         werr = dsdb_convert_object_ex(ldb, working_schema, pfm_remote,
121                                                       cur, gensec_skey,
122                                                       ignore_attids,
123                                                       0,
124                                                       tmp_ctx, &object);
125                         if (!W_ERROR_IS_OK(werr)) {
126                                 DEBUG(4,("debug: Failed to convert schema object %s into ldb msg, will try during next loop\n",
127                                           cur->object.identifier->dn));
128
129                                 failed_obj_count++;
130                         } else {
131                                 /*
132                                  * Convert the schema from ldb_message format
133                                  * (OIDs as OID strings) into schema, using
134                                  * the remote prefixMap
135                                  */
136                                 werr = dsdb_schema_set_el_from_ldb_msg(ldb,
137                                                                        working_schema,
138                                                                        object.msg);
139                                 if (!W_ERROR_IS_OK(werr)) {
140                                         DEBUG(4,("debug: failed to convert object %s into a schema element, will try during next loop: %s\n",
141                                                  ldb_dn_get_linearized(object.msg->dn),
142                                                  win_errstr(werr)));
143                                         failed_obj_count++;
144                                 } else {
145                                         DLIST_REMOVE(schema_list, schema_list_item);
146                                         talloc_free(schema_list_item);
147                                         converted_obj_count++;
148                                 }
149                         }
150                 }
151                 talloc_free(tmp_ctx);
152
153                 DEBUG(4,("Schema load pass %d: converted %d, %d of %d objects left to be converted.\n",
154                          pass_no, converted_obj_count, failed_obj_count, object_count));
155                 pass_no++;
156
157                 /* check if we converted any objects in this pass */
158                 if (converted_obj_count == 0) {
159                         DEBUG(0,("Can't continue Schema load: didn't manage to convert any objects: all %d remaining of %d objects failed to convert\n", failed_obj_count, object_count));
160                         return WERR_INTERNAL_ERROR;
161                 }
162
163                 /* rebuild indexes */
164                 ret = dsdb_setup_sorted_accessors(ldb, working_schema);
165                 if (LDB_SUCCESS != ret) {
166                         DEBUG(0,("Failed to create schema-cache indexes!\n"));
167                         return WERR_INTERNAL_ERROR;
168                 }
169         };
170
171         *_schema_out = working_schema;
172
173         return WERR_OK;
174 }
175
176 static bool dsdb_attid_in_list(const uint32_t attid_list[], uint32_t attid)
177 {
178         const uint32_t *cur;
179         if (!attid_list) {
180                 return false;
181         }
182         for (cur = attid_list; *cur != DRSUAPI_ATTID_INVALID; cur++) {
183                 if (*cur == attid) {
184                         return true;
185                 }
186         }
187         return false;
188 }
189
190 WERROR dsdb_convert_object_ex(struct ldb_context *ldb,
191                               const struct dsdb_schema *schema,
192                               const struct dsdb_schema_prefixmap *pfm_remote,
193                               const struct drsuapi_DsReplicaObjectListItemEx *in,
194                               const DATA_BLOB *gensec_skey,
195                               const uint32_t *ignore_attids,
196                               uint32_t dsdb_repl_flags,
197                               TALLOC_CTX *mem_ctx,
198                               struct dsdb_extended_replicated_object *out)
199 {
200         NTSTATUS nt_status;
201         WERROR status;
202         uint32_t i;
203         struct ldb_message *msg;
204         struct replPropertyMetaDataBlob *md;
205         int instanceType;
206         struct ldb_message_element *instanceType_e = NULL;
207         struct ldb_val guid_value;
208         struct ldb_val parent_guid_value;
209         NTTIME whenChanged = 0;
210         time_t whenChanged_t;
211         const char *whenChanged_s;
212         struct drsuapi_DsReplicaAttribute *name_a = NULL;
213         struct drsuapi_DsReplicaMetaData *name_d = NULL;
214         struct replPropertyMetaData1 *rdn_m = NULL;
215         struct dom_sid *sid = NULL;
216         uint32_t rid = 0;
217         uint32_t attr_count;
218         int ret;
219
220         if (!in->object.identifier) {
221                 return WERR_FOOBAR;
222         }
223
224         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
225                 return WERR_FOOBAR;
226         }
227
228         if (in->object.attribute_ctr.num_attributes != 0 && !in->meta_data_ctr) {
229                 return WERR_FOOBAR;
230         }
231
232         if (in->object.attribute_ctr.num_attributes != in->meta_data_ctr->count) {
233                 return WERR_FOOBAR;
234         }
235
236         sid = &in->object.identifier->sid;
237         if (sid->num_auths > 0) {
238                 rid = sid->sub_auths[sid->num_auths - 1];
239         }
240
241         msg = ldb_msg_new(mem_ctx);
242         W_ERROR_HAVE_NO_MEMORY(msg);
243
244         msg->dn                 = ldb_dn_new(msg, ldb, in->object.identifier->dn);
245         W_ERROR_HAVE_NO_MEMORY(msg->dn);
246
247         msg->num_elements       = in->object.attribute_ctr.num_attributes;
248         msg->elements           = talloc_array(msg, struct ldb_message_element,
249                                                msg->num_elements + 1); /* +1 because of the RDN attribute */
250         W_ERROR_HAVE_NO_MEMORY(msg->elements);
251
252         md = talloc(mem_ctx, struct replPropertyMetaDataBlob);
253         W_ERROR_HAVE_NO_MEMORY(md);
254
255         md->version             = 1;
256         md->reserved            = 0;
257         md->ctr.ctr1.count      = in->meta_data_ctr->count;
258         md->ctr.ctr1.reserved   = 0;
259         md->ctr.ctr1.array      = talloc_array(mem_ctx,
260                                                struct replPropertyMetaData1,
261                                                md->ctr.ctr1.count + 1); /* +1 because of the RDN attribute */
262         W_ERROR_HAVE_NO_MEMORY(md->ctr.ctr1.array);
263
264         for (i=0, attr_count=0; i < in->meta_data_ctr->count; i++, attr_count++) {
265                 struct drsuapi_DsReplicaAttribute *a;
266                 struct drsuapi_DsReplicaMetaData *d;
267                 struct replPropertyMetaData1 *m;
268                 struct ldb_message_element *e;
269                 uint32_t j;
270
271                 a = &in->object.attribute_ctr.attributes[i];
272                 d = &in->meta_data_ctr->meta_data[i];
273                 m = &md->ctr.ctr1.array[attr_count];
274                 e = &msg->elements[attr_count];
275
276                 if (dsdb_attid_in_list(ignore_attids, a->attid)) {
277                         attr_count--;
278                         continue;
279                 }
280
281                 if (a->attid == DRSUAPI_ATTID_instanceType) {
282                         if (instanceType_e != NULL) {
283                                 return WERR_FOOBAR;
284                         }
285                         instanceType_e = e;
286                 }
287
288                 for (j=0; j<a->value_ctr.num_values; j++) {
289                         status = drsuapi_decrypt_attribute(a->value_ctr.values[j].blob, gensec_skey, rid, a);
290                         W_ERROR_NOT_OK_RETURN(status);
291                 }
292
293                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, pfm_remote,
294                                                        a, msg->elements, e);
295                 W_ERROR_NOT_OK_RETURN(status);
296
297                 m->attid                        = a->attid;
298                 m->version                      = d->version;
299                 m->originating_change_time      = d->originating_change_time;
300                 m->originating_invocation_id    = d->originating_invocation_id;
301                 m->originating_usn              = d->originating_usn;
302                 m->local_usn                    = 0;
303
304                 if (d->originating_change_time > whenChanged) {
305                         whenChanged = d->originating_change_time;
306                 }
307
308                 if (a->attid == DRSUAPI_ATTID_name) {
309                         name_a = a;
310                         name_d = d;
311                 }
312         }
313
314         msg->num_elements = attr_count;
315         md->ctr.ctr1.count = attr_count;
316         if (name_a) {
317                 rdn_m = &md->ctr.ctr1.array[md->ctr.ctr1.count];
318         }
319
320         if (rdn_m) {
321                 struct ldb_message_element *el;
322                 const char *rdn_name = NULL;
323                 const struct ldb_val *rdn_value = NULL;
324                 const struct dsdb_attribute *rdn_attr = NULL;
325                 uint32_t rdn_attid;
326
327                 /*
328                  * We only need the schema calls for the RDN in this
329                  * codepath, and by doing this we avoid needing to
330                  * have the dsdb_attribute_by_lDAPDisplayName accessor
331                  * working during the schema load.
332                  */
333                 rdn_name        = ldb_dn_get_rdn_name(msg->dn);
334                 rdn_attr        = dsdb_attribute_by_lDAPDisplayName(schema, rdn_name);
335                 if (!rdn_attr) {
336                         return WERR_FOOBAR;
337                 }
338                 rdn_attid       = rdn_attr->attributeID_id;
339                 rdn_value       = ldb_dn_get_rdn_val(msg->dn);
340
341                 el = ldb_msg_find_element(msg, rdn_attr->lDAPDisplayName);
342                 if (!el) {
343                         ret = ldb_msg_add_value(msg, rdn_attr->lDAPDisplayName, rdn_value, NULL);
344                         if (ret != LDB_SUCCESS) {
345                                 return WERR_FOOBAR;
346                         }
347                 } else {
348                         if (el->num_values != 1) {
349                                 DEBUG(0,(__location__ ": Unexpected num_values=%u\n",
350                                          el->num_values));
351                                 return WERR_FOOBAR;                             
352                         }
353                         if (!ldb_val_equal_exact(&el->values[0], rdn_value)) {
354                                 DEBUG(0,(__location__ ": RDN value changed? '%*.*s' '%*.*s'\n",
355                                          (int)el->values[0].length, (int)el->values[0].length, el->values[0].data,
356                                          (int)rdn_value->length, (int)rdn_value->length, rdn_value->data));
357                                 return WERR_FOOBAR;                             
358                         }
359                 }
360
361                 rdn_m->attid                            = rdn_attid;
362                 rdn_m->version                          = name_d->version;
363                 rdn_m->originating_change_time          = name_d->originating_change_time;
364                 rdn_m->originating_invocation_id        = name_d->originating_invocation_id;
365                 rdn_m->originating_usn                  = name_d->originating_usn;
366                 rdn_m->local_usn                        = 0;
367                 md->ctr.ctr1.count++;
368
369         }
370
371         if (instanceType_e == NULL) {
372                 return WERR_FOOBAR;
373         }
374
375         instanceType = ldb_msg_find_attr_as_int(msg, "instanceType", 0);
376         if (dsdb_repl_flags & DSDB_REPL_FLAG_PARTIAL_REPLICA) {
377                 /* the instanceType type for partial_replica
378                    replication is sent via DRS with TYPE_WRITE set, but
379                    must be used on the client with TYPE_WRITE removed
380                 */
381                 if (instanceType & INSTANCE_TYPE_WRITE) {
382                         /*
383                          * Make sure we do not change the order
384                          * of msg->elements!
385                          *
386                          * That's why we use
387                          * instanceType_e->num_values = 0
388                          * instead of
389                          * ldb_msg_remove_attr(msg, "instanceType");
390                          */
391                         struct ldb_message_element *e;
392
393                         e = ldb_msg_find_element(msg, "instanceType");
394                         if (e != instanceType_e) {
395                                 DEBUG(0,("instanceType_e[%p] changed to e[%p]\n",
396                                          instanceType_e, e));
397                                 return WERR_FOOBAR;
398                         }
399
400                         instanceType_e->num_values = 0;
401
402                         instanceType &= ~INSTANCE_TYPE_WRITE;
403                         if (ldb_msg_add_fmt(msg, "instanceType", "%d", instanceType) != LDB_SUCCESS) {
404                                 return WERR_INTERNAL_ERROR;
405                         }
406                 }
407         } else {
408                 if (!(instanceType & INSTANCE_TYPE_WRITE)) {
409                         DEBUG(0, ("Refusing to replicate %s from a read-only repilca into a read-write replica!\n",
410                                   ldb_dn_get_linearized(msg->dn)));
411                         return WERR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA;
412                 }
413         }
414
415         whenChanged_t = nt_time_to_unix(whenChanged);
416         whenChanged_s = ldb_timestring(msg, whenChanged_t);
417         W_ERROR_HAVE_NO_MEMORY(whenChanged_s);
418
419         nt_status = GUID_to_ndr_blob(&in->object.identifier->guid, msg, &guid_value);
420         if (!NT_STATUS_IS_OK(nt_status)) {
421                 return ntstatus_to_werror(nt_status);
422         }
423
424         if (in->parent_object_guid) {
425                 nt_status = GUID_to_ndr_blob(in->parent_object_guid, msg, &parent_guid_value);
426                 if (!NT_STATUS_IS_OK(nt_status)) {
427                         return ntstatus_to_werror(nt_status);
428                 }
429         } else {
430                 parent_guid_value = data_blob_null;
431         }
432
433         out->msg                = msg;
434         out->guid_value         = guid_value;
435         out->parent_guid_value  = parent_guid_value;
436         out->when_changed       = whenChanged_s;
437         out->meta_data          = md;
438         return WERR_OK;
439 }
440
441 WERROR dsdb_replicated_objects_convert(struct ldb_context *ldb,
442                                        const struct dsdb_schema *schema,
443                                        const char *partition_dn_str,
444                                        const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr,
445                                        uint32_t object_count,
446                                        const struct drsuapi_DsReplicaObjectListItemEx *first_object,
447                                        uint32_t linked_attributes_count,
448                                        const struct drsuapi_DsReplicaLinkedAttribute *linked_attributes,
449                                        const struct repsFromTo1 *source_dsa,
450                                        const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector,
451                                        const DATA_BLOB *gensec_skey,
452                                        uint32_t dsdb_repl_flags,
453                                        TALLOC_CTX *mem_ctx,
454                                        struct dsdb_extended_replicated_objects **objects)
455 {
456         WERROR status;
457         struct ldb_dn *partition_dn;
458         struct dsdb_schema_prefixmap *pfm_remote;
459         struct dsdb_extended_replicated_objects *out;
460         const struct drsuapi_DsReplicaObjectListItemEx *cur;
461         uint32_t i;
462
463         out = talloc_zero(mem_ctx, struct dsdb_extended_replicated_objects);
464         W_ERROR_HAVE_NO_MEMORY(out);
465         out->version            = DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION;
466         out->dsdb_repl_flags    = dsdb_repl_flags;
467
468         /*
469          * Ensure schema is kept valid for as long as 'out'
470          * which may contain pointers to it
471          */
472         schema = talloc_reference(out, schema);
473         W_ERROR_HAVE_NO_MEMORY(schema);
474
475         partition_dn = ldb_dn_new(out, ldb, partition_dn_str);
476         W_ERROR_HAVE_NO_MEMORY_AND_FREE(partition_dn, out);
477
478         status = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
479                                                   out, &pfm_remote, NULL);
480         if (!W_ERROR_IS_OK(status)) {
481                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
482                          win_errstr(status)));
483                 talloc_free(out);
484                 return status;
485         }
486
487         if (ldb_dn_compare(partition_dn, ldb_get_schema_basedn(ldb)) != 0) {
488                 /*
489                  * check for schema changes in case
490                  * we are not replicating Schema NC
491                  */
492                 status = dsdb_schema_info_cmp(schema, mapping_ctr);
493                 if (!W_ERROR_IS_OK(status)) {
494                         DEBUG(1,("Remote schema has changed while replicating %s\n",
495                                  partition_dn_str));
496                         talloc_free(out);
497                         return status;
498                 }
499         }
500
501         out->partition_dn       = partition_dn;
502
503         out->source_dsa         = source_dsa;
504         out->uptodateness_vector= uptodateness_vector;
505
506         out->num_objects        = object_count;
507         out->objects            = talloc_array(out,
508                                                struct dsdb_extended_replicated_object,
509                                                out->num_objects);
510         W_ERROR_HAVE_NO_MEMORY_AND_FREE(out->objects, out);
511
512         /* pass the linked attributes down to the repl_meta_data
513            module */
514         out->linked_attributes_count = linked_attributes_count;
515         out->linked_attributes       = linked_attributes;
516
517         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
518                 if (i == out->num_objects) {
519                         talloc_free(out);
520                         return WERR_FOOBAR;
521                 }
522
523                 status = dsdb_convert_object_ex(ldb, schema, pfm_remote,
524                                                 cur, gensec_skey,
525                                                 NULL,
526                                                 dsdb_repl_flags,
527                                                 out->objects, &out->objects[i]);
528                 if (!W_ERROR_IS_OK(status)) {
529                         talloc_free(out);
530                         DEBUG(0,("Failed to convert object %s: %s\n",
531                                  cur->object.identifier->dn,
532                                  win_errstr(status)));
533                         return status;
534                 }
535         }
536         if (i != out->num_objects) {
537                 talloc_free(out);
538                 return WERR_FOOBAR;
539         }
540
541         /* free pfm_remote, we won't need it anymore */
542         talloc_free(pfm_remote);
543
544         *objects = out;
545         return WERR_OK;
546 }
547
548 /**
549  * Commits a list of replicated objects.
550  *
551  * @param working_schema dsdb_schema to be used for resolving
552  *                       Classes/Attributes during Schema replication. If not NULL,
553  *                       it will be set on ldb and used while committing replicated objects
554  */
555 WERROR dsdb_replicated_objects_commit(struct ldb_context *ldb,
556                                       struct dsdb_schema *working_schema,
557                                       struct dsdb_extended_replicated_objects *objects,
558                                       uint64_t *notify_uSN)
559 {
560         WERROR werr;
561         struct ldb_result *ext_res;
562         struct dsdb_schema *cur_schema = NULL;
563         struct dsdb_schema *new_schema = NULL;
564         int ret;
565         uint64_t seq_num1, seq_num2;
566         bool used_global_schema = false;
567
568         TALLOC_CTX *tmp_ctx = talloc_new(objects);
569         if (!tmp_ctx) {
570                 DEBUG(0,("Failed to start talloc\n"));
571                 return WERR_NOMEM;
572         }
573
574         /* TODO: handle linked attributes */
575
576         /* wrap the extended operation in a transaction 
577            See [MS-DRSR] 3.3.2 Transactions
578          */
579         ret = ldb_transaction_start(ldb);
580         if (ret != LDB_SUCCESS) {
581                 DEBUG(0,(__location__ " Failed to start transaction\n"));
582                 return WERR_FOOBAR;
583         }
584
585         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num1, NULL);
586         if (ret != LDB_SUCCESS) {
587                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
588                 ldb_transaction_cancel(ldb);
589                 TALLOC_FREE(tmp_ctx);
590                 return WERR_FOOBAR;             
591         }
592
593         /*
594          * Set working_schema for ldb in case we are replicating from Schema NC.
595          * Schema won't be reloaded during Replicated Objects commit, as it is
596          * done in a transaction. So we need some way to search for newly
597          * added Classes and Attributes
598          */
599         if (working_schema) {
600                 /* store current schema so we can fall back in case of failure */
601                 cur_schema = dsdb_get_schema(ldb, tmp_ctx);
602                 used_global_schema = dsdb_uses_global_schema(ldb);
603
604                 ret = dsdb_reference_schema(ldb, working_schema, false);
605                 if (ret != LDB_SUCCESS) {
606                         DEBUG(0,(__location__ "Failed to reference working schema - %s\n",
607                                  ldb_strerror(ret)));
608                         /* TODO: Map LDB Error to NTSTATUS? */
609                         ldb_transaction_cancel(ldb);
610                         TALLOC_FREE(tmp_ctx);
611                         return WERR_INTERNAL_ERROR;
612                 }
613         }
614
615         ret = ldb_extended(ldb, DSDB_EXTENDED_REPLICATED_OBJECTS_OID, objects, &ext_res);
616         if (ret != LDB_SUCCESS) {
617                 /* restore previous schema */
618                 if (used_global_schema) { 
619                         dsdb_set_global_schema(ldb);
620                 } else if (cur_schema) {
621                         dsdb_reference_schema(ldb, cur_schema, false);
622                 }
623
624                 DEBUG(0,("Failed to apply records: %s: %s\n",
625                          ldb_errstring(ldb), ldb_strerror(ret)));
626                 ldb_transaction_cancel(ldb);
627                 TALLOC_FREE(tmp_ctx);
628                 return WERR_FOOBAR;
629         }
630         talloc_free(ext_res);
631
632         /* Save our updated prefixMap */
633         if (working_schema) {
634                 werr = dsdb_write_prefixes_from_schema_to_ldb(working_schema,
635                                                               ldb,
636                                                               working_schema);
637                 if (!W_ERROR_IS_OK(werr)) {
638                         /* restore previous schema */
639                         if (used_global_schema) { 
640                                 dsdb_set_global_schema(ldb);
641                         } else if (cur_schema ) {
642                                 dsdb_reference_schema(ldb, cur_schema, false);
643                         }
644                         DEBUG(0,("Failed to save updated prefixMap: %s\n",
645                                  win_errstr(werr)));
646                         TALLOC_FREE(tmp_ctx);
647                         return werr;
648                 }
649         }
650
651         ret = ldb_transaction_prepare_commit(ldb);
652         if (ret != LDB_SUCCESS) {
653                 /* restore previous schema */
654                 if (used_global_schema) { 
655                         dsdb_set_global_schema(ldb);
656                 } else if (cur_schema ) {
657                         dsdb_reference_schema(ldb, cur_schema, false);
658                 }
659                 DEBUG(0,(__location__ " Failed to prepare commit of transaction: %s\n",
660                          ldb_errstring(ldb)));
661                 TALLOC_FREE(tmp_ctx);
662                 return WERR_FOOBAR;
663         }
664
665         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num2, NULL);
666         if (ret != LDB_SUCCESS) {
667                 /* restore previous schema */
668                 if (used_global_schema) { 
669                         dsdb_set_global_schema(ldb);
670                 } else if (cur_schema ) {
671                         dsdb_reference_schema(ldb, cur_schema, false);
672                 }
673                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
674                 ldb_transaction_cancel(ldb);
675                 TALLOC_FREE(tmp_ctx);
676                 return WERR_FOOBAR;             
677         }
678
679         /* if this replication partner didn't need to be notified
680            before this transaction then it still doesn't need to be
681            notified, as the changes came from this server */    
682         if (seq_num2 > seq_num1 && seq_num1 <= *notify_uSN) {
683                 *notify_uSN = seq_num2;
684         }
685
686         ret = ldb_transaction_commit(ldb);
687         if (ret != LDB_SUCCESS) {
688                 /* restore previous schema */
689                 if (used_global_schema) { 
690                         dsdb_set_global_schema(ldb);
691                 } else if (cur_schema ) {
692                         dsdb_reference_schema(ldb, cur_schema, false);
693                 }
694                 DEBUG(0,(__location__ " Failed to commit transaction\n"));
695                 TALLOC_FREE(tmp_ctx);
696                 return WERR_FOOBAR;
697         }
698
699         /*
700          * Reset the Schema used by ldb. This will lead to
701          * a schema cache being refreshed from database.
702          */
703         if (working_schema) {
704                 struct ldb_message *msg;
705                 struct ldb_request *req;
706
707                 /* Force a reload */
708                 working_schema->last_refresh = 0;
709                 new_schema = dsdb_get_schema(ldb, tmp_ctx);
710                 /* TODO: 
711                  * If dsdb_get_schema() fails, we just fall back
712                  * to what we had.  However, the database is probably
713                  * unable to operate for other users from this
714                  * point... */
715                 if (new_schema && used_global_schema) {
716                         dsdb_make_schema_global(ldb, new_schema);
717                 } else if (used_global_schema) { 
718                         DEBUG(0,("Failed to re-load schema after commit of transaction\n"));
719                         dsdb_set_global_schema(ldb);
720                         TALLOC_FREE(tmp_ctx);
721                         return WERR_INTERNAL_ERROR;
722                 } else {
723                         DEBUG(0,("Failed to re-load schema after commit of transaction\n"));
724                         dsdb_reference_schema(ldb, cur_schema, false);
725                         TALLOC_FREE(tmp_ctx);
726                         return WERR_INTERNAL_ERROR;
727                 }
728                 msg = ldb_msg_new(tmp_ctx);
729                 if (msg == NULL) {
730                         TALLOC_FREE(tmp_ctx);
731                         return WERR_NOMEM;
732                 }
733                 msg->dn = ldb_dn_new(msg, ldb, "");
734                 if (msg->dn == NULL) {
735                         TALLOC_FREE(tmp_ctx);
736                         return WERR_NOMEM;
737                 }
738
739                 ret = ldb_msg_add_string(msg, "schemaUpdateNow", "1");
740                 if (ret != LDB_SUCCESS) {
741                         TALLOC_FREE(tmp_ctx);
742                         return WERR_INTERNAL_ERROR;
743                 }
744
745                 ret = ldb_build_mod_req(&req, ldb, objects,
746                                 msg,
747                                 LDB_SCOPE_BASE,
748                                 NULL,
749                                 ldb_op_default_callback,
750                                 NULL);
751
752                 if (ret != LDB_SUCCESS) {
753                         TALLOC_FREE(tmp_ctx);
754                         return WERR_DS_DRA_INTERNAL_ERROR;
755                 }
756
757                 ret = ldb_transaction_start(ldb);
758                 if (ret != LDB_SUCCESS) {
759                         TALLOC_FREE(tmp_ctx);
760                         DEBUG(0, ("Autotransaction start failed\n"));
761                         return WERR_DS_DRA_INTERNAL_ERROR;
762                 }
763
764                 ret = ldb_request(ldb, req);
765                 if (ret == LDB_SUCCESS) {
766                         ret = ldb_wait(req->handle, LDB_WAIT_ALL);
767                 }
768
769                 if (ret == LDB_SUCCESS) {
770                         ret = ldb_transaction_commit(ldb);
771                 } else {
772                         DEBUG(0, ("Schema update now failed: %s\n",
773                                   ldb_errstring(ldb)));
774                         ldb_transaction_cancel(ldb);
775                 }
776
777                 if (ret != LDB_SUCCESS) {
778                         DEBUG(0, ("Commit failed: %s\n", ldb_errstring(ldb)));
779                         TALLOC_FREE(tmp_ctx);
780                         return WERR_DS_INTERNAL_FAILURE;
781                 }
782         }
783
784         DEBUG(2,("Replicated %u objects (%u linked attributes) for %s\n",
785                  objects->num_objects, objects->linked_attributes_count,
786                  ldb_dn_get_linearized(objects->partition_dn)));
787                  
788         TALLOC_FREE(tmp_ctx);
789         return WERR_OK;
790 }
791
792 static WERROR dsdb_origin_object_convert(struct ldb_context *ldb,
793                                          const struct dsdb_schema *schema,
794                                          const struct drsuapi_DsReplicaObjectListItem *in,
795                                          TALLOC_CTX *mem_ctx,
796                                          struct ldb_message **_msg)
797 {
798         WERROR status;
799         unsigned int i;
800         struct ldb_message *msg;
801
802         if (!in->object.identifier) {
803                 return WERR_FOOBAR;
804         }
805
806         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
807                 return WERR_FOOBAR;
808         }
809
810         msg = ldb_msg_new(mem_ctx);
811         W_ERROR_HAVE_NO_MEMORY(msg);
812
813         msg->dn = ldb_dn_new(msg, ldb, in->object.identifier->dn);
814         W_ERROR_HAVE_NO_MEMORY(msg->dn);
815
816         msg->num_elements       = in->object.attribute_ctr.num_attributes;
817         msg->elements           = talloc_array(msg, struct ldb_message_element,
818                                                msg->num_elements);
819         W_ERROR_HAVE_NO_MEMORY(msg->elements);
820
821         for (i=0; i < msg->num_elements; i++) {
822                 struct drsuapi_DsReplicaAttribute *a;
823                 struct ldb_message_element *e;
824
825                 a = &in->object.attribute_ctr.attributes[i];
826                 e = &msg->elements[i];
827
828                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, schema->prefixmap,
829                                                        a, msg->elements, e);
830                 W_ERROR_NOT_OK_RETURN(status);
831         }
832
833
834         *_msg = msg;
835
836         return WERR_OK;
837 }
838
839 WERROR dsdb_origin_objects_commit(struct ldb_context *ldb,
840                                   TALLOC_CTX *mem_ctx,
841                                   const struct drsuapi_DsReplicaObjectListItem *first_object,
842                                   uint32_t *_num,
843                                   uint32_t dsdb_repl_flags,
844                                   struct drsuapi_DsReplicaObjectIdentifier2 **_ids)
845 {
846         WERROR status;
847         const struct dsdb_schema *schema;
848         const struct drsuapi_DsReplicaObjectListItem *cur;
849         struct ldb_message **objects;
850         struct drsuapi_DsReplicaObjectIdentifier2 *ids;
851         uint32_t i;
852         uint32_t num_objects = 0;
853         const char * const attrs[] = {
854                 "objectGUID",
855                 "objectSid",
856                 NULL
857         };
858         struct ldb_result *res;
859         int ret;
860
861         for (cur = first_object; cur; cur = cur->next_object) {
862                 num_objects++;
863         }
864
865         if (num_objects == 0) {
866                 return WERR_OK;
867         }
868
869         ret = ldb_transaction_start(ldb);
870         if (ret != LDB_SUCCESS) {
871                 return WERR_DS_INTERNAL_FAILURE;
872         }
873
874         objects = talloc_array(mem_ctx, struct ldb_message *,
875                                num_objects);
876         if (objects == NULL) {
877                 status = WERR_NOMEM;
878                 goto cancel;
879         }
880
881         schema = dsdb_get_schema(ldb, objects);
882         if (!schema) {
883                 return WERR_DS_SCHEMA_NOT_LOADED;
884         }
885
886         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
887                 status = dsdb_origin_object_convert(ldb, schema, cur,
888                                                     objects, &objects[i]);
889                 if (!W_ERROR_IS_OK(status)) {
890                         goto cancel;
891                 }
892         }
893
894         ids = talloc_array(mem_ctx,
895                            struct drsuapi_DsReplicaObjectIdentifier2,
896                            num_objects);
897         if (ids == NULL) {
898                 status = WERR_NOMEM;
899                 goto cancel;
900         }
901
902         if (dsdb_repl_flags & DSDB_REPL_FLAG_ADD_NCNAME) {
903                 /* check for possible NC creation */
904                 for (i=0; i < num_objects; i++) {
905                         struct ldb_message *msg = objects[i];
906                         struct ldb_message_element *el;
907                         struct ldb_dn *nc_dn;
908
909                         if (ldb_msg_check_string_attribute(msg, "objectClass", "crossRef") == 0) {
910                                 continue;
911                         }
912                         el = ldb_msg_find_element(msg, "nCName");
913                         if (el == NULL || el->num_values != 1) {
914                                 continue;
915                         }
916                         nc_dn = ldb_dn_from_ldb_val(objects, ldb, &el->values[0]);
917                         if (!ldb_dn_validate(nc_dn)) {
918                                 continue;
919                         }
920                         ret = dsdb_create_partial_replica_NC(ldb, nc_dn);
921                         if (ret != LDB_SUCCESS) {
922                                 status = WERR_DS_INTERNAL_FAILURE;
923                                 goto cancel;
924                         }
925                 }
926         }
927
928         for (i=0; i < num_objects; i++) {
929                 struct dom_sid *sid = NULL;
930                 struct ldb_request *add_req;
931
932                 DEBUG(6,(__location__ ": adding %s\n", 
933                          ldb_dn_get_linearized(objects[i]->dn)));
934
935                 ret = ldb_build_add_req(&add_req,
936                                         ldb,
937                                         objects,
938                                         objects[i],
939                                         NULL,
940                                         NULL,
941                                         ldb_op_default_callback,
942                                         NULL);
943                 if (ret != LDB_SUCCESS) {
944                         status = WERR_DS_INTERNAL_FAILURE;
945                         goto cancel;
946                 }
947
948                 ret = ldb_request_add_control(add_req, LDB_CONTROL_RELAX_OID, true, NULL);
949                 if (ret != LDB_SUCCESS) {
950                         status = WERR_DS_INTERNAL_FAILURE;
951                         goto cancel;
952                 }
953                 
954                 ret = ldb_request(ldb, add_req);
955                 if (ret == LDB_SUCCESS) {
956                         ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
957                 }
958                 if (ret != LDB_SUCCESS) {
959                         DEBUG(0,(__location__ ": Failed add of %s - %s\n",
960                                  ldb_dn_get_linearized(objects[i]->dn), ldb_errstring(ldb)));
961                         status = WERR_DS_INTERNAL_FAILURE;
962                         goto cancel;
963                 }
964
965                 talloc_free(add_req);
966
967                 ret = ldb_search(ldb, objects, &res, objects[i]->dn,
968                                  LDB_SCOPE_BASE, attrs,
969                                  "(objectClass=*)");
970                 if (ret != LDB_SUCCESS) {
971                         status = WERR_DS_INTERNAL_FAILURE;
972                         goto cancel;
973                 }
974                 ids[i].guid = samdb_result_guid(res->msgs[0], "objectGUID");
975                 sid = samdb_result_dom_sid(objects, res->msgs[0], "objectSid");
976                 if (sid) {
977                         ids[i].sid = *sid;
978                 } else {
979                         ZERO_STRUCT(ids[i].sid);
980                 }
981         }
982
983         ret = ldb_transaction_commit(ldb);
984         if (ret != LDB_SUCCESS) {
985                 return WERR_DS_INTERNAL_FAILURE;
986         }
987
988         talloc_free(objects);
989
990         *_num = num_objects;
991         *_ids = ids;
992         return WERR_OK;
993
994 cancel:
995         talloc_free(objects);
996         ldb_transaction_cancel(ldb);
997         return status;
998 }