s4-dsdb: Use parent_object_guid to find the correct parent for new objects
[mat/samba.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: %d/%d of %d objects left to be converted.\n",
154                          pass_no, failed_obj_count, converted_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         struct ldb_val guid_value;
206         struct ldb_val parent_guid_value;
207         NTTIME whenChanged = 0;
208         time_t whenChanged_t;
209         const char *whenChanged_s;
210         const char *rdn_name = NULL;
211         const struct ldb_val *rdn_value = NULL;
212         const struct dsdb_attribute *rdn_attr = NULL;
213         uint32_t rdn_attid;
214         struct drsuapi_DsReplicaAttribute *name_a = NULL;
215         struct drsuapi_DsReplicaMetaData *name_d = NULL;
216         struct replPropertyMetaData1 *rdn_m = NULL;
217         struct dom_sid *sid = NULL;
218         uint32_t rid = 0;
219         uint32_t attr_count;
220         int ret;
221
222         if (!in->object.identifier) {
223                 return WERR_FOOBAR;
224         }
225
226         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
227                 return WERR_FOOBAR;
228         }
229
230         if (in->object.attribute_ctr.num_attributes != 0 && !in->meta_data_ctr) {
231                 return WERR_FOOBAR;
232         }
233
234         if (in->object.attribute_ctr.num_attributes != in->meta_data_ctr->count) {
235                 return WERR_FOOBAR;
236         }
237
238         sid = &in->object.identifier->sid;
239         if (sid->num_auths > 0) {
240                 rid = sid->sub_auths[sid->num_auths - 1];
241         }
242
243         msg = ldb_msg_new(mem_ctx);
244         W_ERROR_HAVE_NO_MEMORY(msg);
245
246         msg->dn                 = ldb_dn_new(msg, ldb, in->object.identifier->dn);
247         W_ERROR_HAVE_NO_MEMORY(msg->dn);
248
249         rdn_name        = ldb_dn_get_rdn_name(msg->dn);
250         rdn_attr        = dsdb_attribute_by_lDAPDisplayName(schema, rdn_name);
251         if (!rdn_attr) {
252                 return WERR_FOOBAR;
253         }
254         rdn_attid       = rdn_attr->attributeID_id;
255         rdn_value       = ldb_dn_get_rdn_val(msg->dn);
256
257         msg->num_elements       = in->object.attribute_ctr.num_attributes;
258         msg->elements           = talloc_array(msg, struct ldb_message_element,
259                                                msg->num_elements);
260         W_ERROR_HAVE_NO_MEMORY(msg->elements);
261
262         md = talloc(mem_ctx, struct replPropertyMetaDataBlob);
263         W_ERROR_HAVE_NO_MEMORY(md);
264
265         md->version             = 1;
266         md->reserved            = 0;
267         md->ctr.ctr1.count      = in->meta_data_ctr->count;
268         md->ctr.ctr1.reserved   = 0;
269         md->ctr.ctr1.array      = talloc_array(mem_ctx,
270                                                struct replPropertyMetaData1,
271                                                md->ctr.ctr1.count + 1); /* +1 because of the RDN attribute */
272         W_ERROR_HAVE_NO_MEMORY(md->ctr.ctr1.array);
273
274         for (i=0, attr_count=0; i < in->meta_data_ctr->count; i++, attr_count++) {
275                 struct drsuapi_DsReplicaAttribute *a;
276                 struct drsuapi_DsReplicaMetaData *d;
277                 struct replPropertyMetaData1 *m;
278                 struct ldb_message_element *e;
279                 uint32_t j;
280
281                 a = &in->object.attribute_ctr.attributes[i];
282                 d = &in->meta_data_ctr->meta_data[i];
283                 m = &md->ctr.ctr1.array[attr_count];
284                 e = &msg->elements[attr_count];
285
286                 if (dsdb_attid_in_list(ignore_attids, a->attid)) {
287                         attr_count--;
288                         continue;
289                 }
290
291                 for (j=0; j<a->value_ctr.num_values; j++) {
292                         status = drsuapi_decrypt_attribute(a->value_ctr.values[j].blob, gensec_skey, rid, a);
293                         W_ERROR_NOT_OK_RETURN(status);
294                 }
295
296                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, pfm_remote,
297                                                        a, msg->elements, e);
298                 W_ERROR_NOT_OK_RETURN(status);
299
300                 m->attid                        = a->attid;
301                 m->version                      = d->version;
302                 m->originating_change_time      = d->originating_change_time;
303                 m->originating_invocation_id    = d->originating_invocation_id;
304                 m->originating_usn              = d->originating_usn;
305                 m->local_usn                    = 0;
306
307                 if (d->originating_change_time > whenChanged) {
308                         whenChanged = d->originating_change_time;
309                 }
310
311                 if (a->attid == DRSUAPI_ATTID_name) {
312                         name_a = a;
313                         name_d = d;
314                 }
315         }
316
317         msg->num_elements = attr_count;
318         md->ctr.ctr1.count = attr_count;
319         if (name_a) {
320                 rdn_m = &md->ctr.ctr1.array[md->ctr.ctr1.count];
321         }
322
323         if (rdn_m) {
324                 struct ldb_message_element *el;
325                 el = ldb_msg_find_element(msg, rdn_attr->lDAPDisplayName);
326                 if (!el) {
327                         ret = ldb_msg_add_value(msg, rdn_attr->lDAPDisplayName, rdn_value, NULL);
328                         if (ret != LDB_SUCCESS) {
329                                 return WERR_FOOBAR;
330                         }
331                 } else {
332                         if (el->num_values != 1) {
333                                 DEBUG(0,(__location__ ": Unexpected num_values=%u\n",
334                                          el->num_values));
335                                 return WERR_FOOBAR;                             
336                         }
337                         if (!ldb_val_equal_exact(&el->values[0], rdn_value)) {
338                                 DEBUG(0,(__location__ ": RDN value changed? '%*.*s' '%*.*s'\n",
339                                          (int)el->values[0].length, (int)el->values[0].length, el->values[0].data,
340                                          (int)rdn_value->length, (int)rdn_value->length, rdn_value->data));
341                                 return WERR_FOOBAR;                             
342                         }
343                 }
344
345                 rdn_m->attid                            = rdn_attid;
346                 rdn_m->version                          = name_d->version;
347                 rdn_m->originating_change_time          = name_d->originating_change_time;
348                 rdn_m->originating_invocation_id        = name_d->originating_invocation_id;
349                 rdn_m->originating_usn                  = name_d->originating_usn;
350                 rdn_m->local_usn                        = 0;
351                 md->ctr.ctr1.count++;
352
353         }
354
355         if (dsdb_repl_flags & DSDB_REPL_FLAG_PARTIAL_REPLICA) {
356                 /* the instanceType type for partial_replica
357                    replication is sent via DRS with TYPE_WRITE set, but
358                    must be used on the client with TYPE_WRITE removed
359                 */
360                 int instanceType = ldb_msg_find_attr_as_int(msg, "instanceType", 0);
361                 if (instanceType & INSTANCE_TYPE_WRITE) {
362                         instanceType &= ~INSTANCE_TYPE_WRITE;
363                         ldb_msg_remove_attr(msg, "instanceType");
364                         if (ldb_msg_add_fmt(msg, "instanceType", "%d", instanceType) != LDB_SUCCESS) {
365                                 return WERR_INTERNAL_ERROR;
366                         }
367                 }
368         }
369
370         whenChanged_t = nt_time_to_unix(whenChanged);
371         whenChanged_s = ldb_timestring(msg, whenChanged_t);
372         W_ERROR_HAVE_NO_MEMORY(whenChanged_s);
373
374         nt_status = GUID_to_ndr_blob(&in->object.identifier->guid, msg, &guid_value);
375         if (!NT_STATUS_IS_OK(nt_status)) {
376                 return ntstatus_to_werror(nt_status);
377         }
378
379         if (in->parent_object_guid) {
380                 nt_status = GUID_to_ndr_blob(in->parent_object_guid, msg, &parent_guid_value);
381                 if (!NT_STATUS_IS_OK(nt_status)) {
382                         return ntstatus_to_werror(nt_status);
383                 }
384         } else {
385                 parent_guid_value = data_blob_null;
386         }
387
388         out->msg                = msg;
389         out->guid_value         = guid_value;
390         out->parent_guid_value  = parent_guid_value;
391         out->when_changed       = whenChanged_s;
392         out->meta_data          = md;
393         return WERR_OK;
394 }
395
396 WERROR dsdb_replicated_objects_convert(struct ldb_context *ldb,
397                                        const struct dsdb_schema *schema,
398                                        const char *partition_dn_str,
399                                        const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr,
400                                        uint32_t object_count,
401                                        const struct drsuapi_DsReplicaObjectListItemEx *first_object,
402                                        uint32_t linked_attributes_count,
403                                        const struct drsuapi_DsReplicaLinkedAttribute *linked_attributes,
404                                        const struct repsFromTo1 *source_dsa,
405                                        const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector,
406                                        const DATA_BLOB *gensec_skey,
407                                        uint32_t dsdb_repl_flags,
408                                        TALLOC_CTX *mem_ctx,
409                                        struct dsdb_extended_replicated_objects **objects)
410 {
411         WERROR status;
412         struct ldb_dn *partition_dn;
413         struct dsdb_schema_prefixmap *pfm_remote;
414         struct dsdb_extended_replicated_objects *out;
415         const struct drsuapi_DsReplicaObjectListItemEx *cur;
416         uint32_t i;
417
418         out = talloc_zero(mem_ctx, struct dsdb_extended_replicated_objects);
419         W_ERROR_HAVE_NO_MEMORY(out);
420         out->version            = DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION;
421         out->dsdb_repl_flags    = dsdb_repl_flags;
422
423         /*
424          * Ensure schema is kept valid for as long as 'out'
425          * which may contain pointers to it
426          */
427         schema = talloc_reference(out, schema);
428         W_ERROR_HAVE_NO_MEMORY(schema);
429
430         partition_dn = ldb_dn_new(out, ldb, partition_dn_str);
431         W_ERROR_HAVE_NO_MEMORY_AND_FREE(partition_dn, out);
432
433         status = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
434                                                   out, &pfm_remote, NULL);
435         if (!W_ERROR_IS_OK(status)) {
436                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
437                          win_errstr(status)));
438                 talloc_free(out);
439                 return status;
440         }
441
442         if (ldb_dn_compare(partition_dn, ldb_get_schema_basedn(ldb)) != 0) {
443                 /*
444                  * check for schema changes in case
445                  * we are not replicating Schema NC
446                  */
447                 status = dsdb_schema_info_cmp(schema, mapping_ctr);
448                 if (!W_ERROR_IS_OK(status)) {
449                         DEBUG(1,("Remote schema has changed while replicating %s\n",
450                                  partition_dn_str));
451                         talloc_free(out);
452                         return status;
453                 }
454         }
455
456         out->partition_dn       = partition_dn;
457
458         out->source_dsa         = source_dsa;
459         out->uptodateness_vector= uptodateness_vector;
460
461         out->num_objects        = object_count;
462         out->objects            = talloc_array(out,
463                                                struct dsdb_extended_replicated_object,
464                                                out->num_objects);
465         W_ERROR_HAVE_NO_MEMORY_AND_FREE(out->objects, out);
466
467         /* pass the linked attributes down to the repl_meta_data
468            module */
469         out->linked_attributes_count = linked_attributes_count;
470         out->linked_attributes       = linked_attributes;
471
472         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
473                 if (i == out->num_objects) {
474                         talloc_free(out);
475                         return WERR_FOOBAR;
476                 }
477
478                 status = dsdb_convert_object_ex(ldb, schema, pfm_remote,
479                                                 cur, gensec_skey,
480                                                 NULL,
481                                                 dsdb_repl_flags,
482                                                 out->objects, &out->objects[i]);
483                 if (!W_ERROR_IS_OK(status)) {
484                         talloc_free(out);
485                         DEBUG(0,("Failed to convert object %s: %s\n",
486                                  cur->object.identifier->dn,
487                                  win_errstr(status)));
488                         return status;
489                 }
490         }
491         if (i != out->num_objects) {
492                 talloc_free(out);
493                 return WERR_FOOBAR;
494         }
495
496         /* free pfm_remote, we won't need it anymore */
497         talloc_free(pfm_remote);
498
499         *objects = out;
500         return WERR_OK;
501 }
502
503 /**
504  * Commits a list of replicated objects.
505  *
506  * @param working_schema dsdb_schema to be used for resolving
507  *                       Classes/Attributes during Schema replication. If not NULL,
508  *                       it will be set on ldb and used while committing replicated objects
509  */
510 WERROR dsdb_replicated_objects_commit(struct ldb_context *ldb,
511                                       struct dsdb_schema *working_schema,
512                                       struct dsdb_extended_replicated_objects *objects,
513                                       uint64_t *notify_uSN)
514 {
515         WERROR werr;
516         struct ldb_result *ext_res;
517         struct dsdb_schema *cur_schema = NULL;
518         int ret;
519         uint64_t seq_num1, seq_num2;
520
521         /* TODO: handle linked attributes */
522
523         /* wrap the extended operation in a transaction 
524            See [MS-DRSR] 3.3.2 Transactions
525          */
526         ret = ldb_transaction_start(ldb);
527         if (ret != LDB_SUCCESS) {
528                 DEBUG(0,(__location__ " Failed to start transaction\n"));
529                 return WERR_FOOBAR;
530         }
531
532         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num1, NULL);
533         if (ret != LDB_SUCCESS) {
534                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
535                 ldb_transaction_cancel(ldb);
536                 return WERR_FOOBAR;             
537         }
538
539         /*
540          * Set working_schema for ldb in case we are replicating from Schema NC.
541          * Schema won't be reloaded during Replicated Objects commit, as it is
542          * done in a transaction. So we need some way to search for newly
543          * added Classes and Attributes
544          */
545         if (working_schema) {
546                 /* store current schema so we can fall back in case of failure */
547                 cur_schema = dsdb_get_schema(ldb, working_schema);
548
549                 ret = dsdb_reference_schema(ldb, working_schema, false);
550                 if (ret != LDB_SUCCESS) {
551                         DEBUG(0,(__location__ "Failed to reference working schema - %s\n",
552                                  ldb_strerror(ret)));
553                         /* TODO: Map LDB Error to NTSTATUS? */
554                         ldb_transaction_cancel(ldb);
555                         return WERR_INTERNAL_ERROR;
556                 }
557         }
558
559         ret = ldb_extended(ldb, DSDB_EXTENDED_REPLICATED_OBJECTS_OID, objects, &ext_res);
560         if (ret != LDB_SUCCESS) {
561                 /* restore previous schema */
562                 if (cur_schema ) {
563                         dsdb_reference_schema(ldb, cur_schema, false);
564                         dsdb_make_schema_global(ldb, cur_schema);
565                 }
566
567                 DEBUG(0,("Failed to apply records: %s: %s\n",
568                          ldb_errstring(ldb), ldb_strerror(ret)));
569                 ldb_transaction_cancel(ldb);
570                 return WERR_FOOBAR;
571         }
572         talloc_free(ext_res);
573
574         /* Save our updated prefixMap */
575         if (working_schema) {
576                 werr = dsdb_write_prefixes_from_schema_to_ldb(working_schema,
577                                                               ldb,
578                                                               working_schema);
579                 if (!W_ERROR_IS_OK(werr)) {
580                         /* restore previous schema */
581                         if (cur_schema ) {
582                                 dsdb_reference_schema(ldb, cur_schema, false);
583                                 dsdb_make_schema_global(ldb, cur_schema);
584                         }
585                         DEBUG(0,("Failed to save updated prefixMap: %s\n",
586                                  win_errstr(werr)));
587                         return werr;
588                 }
589         }
590
591         ret = ldb_transaction_prepare_commit(ldb);
592         if (ret != LDB_SUCCESS) {
593                 /* restore previous schema */
594                 if (cur_schema ) {
595                         dsdb_reference_schema(ldb, cur_schema, false);
596                         dsdb_make_schema_global(ldb, cur_schema);
597                 }
598                 DEBUG(0,(__location__ " Failed to prepare commit of transaction: %s\n",
599                          ldb_errstring(ldb)));
600                 return WERR_FOOBAR;
601         }
602
603         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num2, NULL);
604         if (ret != LDB_SUCCESS) {
605                 /* restore previous schema */
606                 if (cur_schema ) {
607                         dsdb_reference_schema(ldb, cur_schema, false);
608                         dsdb_make_schema_global(ldb, cur_schema);
609                 }
610                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
611                 ldb_transaction_cancel(ldb);
612                 return WERR_FOOBAR;             
613         }
614
615         /* if this replication partner didn't need to be notified
616            before this transaction then it still doesn't need to be
617            notified, as the changes came from this server */    
618         if (seq_num2 > seq_num1 && seq_num1 <= *notify_uSN) {
619                 *notify_uSN = seq_num2;
620         }
621
622         ret = ldb_transaction_commit(ldb);
623         if (ret != LDB_SUCCESS) {
624                 /* restore previous schema */
625                 if (cur_schema ) {
626                         dsdb_reference_schema(ldb, cur_schema, false);
627                         dsdb_make_schema_global(ldb, cur_schema);
628                 }
629                 DEBUG(0,(__location__ " Failed to commit transaction\n"));
630                 return WERR_FOOBAR;
631         }
632
633         /*
634          * Reset the Schema used by ldb. This will lead to
635          * a schema cache being refreshed from database.
636          */
637         if (working_schema) {
638                 struct ldb_message *msg;
639                 struct ldb_request *req;
640
641                 /* Force a reload */
642                 working_schema->last_refresh = 0;
643                 cur_schema = dsdb_get_schema(ldb, NULL);
644                 /* TODO: What we do in case dsdb_get_schema() fail?
645                  *       We can't fallback at this point anymore */
646                 if (cur_schema) {
647                         dsdb_make_schema_global(ldb, cur_schema);
648                 }
649                 msg = ldb_msg_new(ldb);
650                 if (msg == 0) {
651                         return WERR_NOMEM;
652                 }
653                 msg->dn = NULL;
654
655                 ret = ldb_msg_add_string(msg, "schemaUpdateNow", "1");
656                 if (ret != LDB_SUCCESS) {
657                         talloc_free(msg);
658                         return WERR_INTERNAL_ERROR;
659                 }
660
661                 ret = ldb_build_mod_req(&req, ldb, ldb,
662                                 msg,
663                                 LDB_SCOPE_BASE,
664                                 NULL,
665                                 ldb_op_default_callback,
666                                 NULL);
667
668                 if (ret != LDB_SUCCESS) {
669                         talloc_free(msg);
670                         return WERR_DS_DRA_INTERNAL_ERROR;
671                 }
672
673                 ret = ldb_transaction_start(ldb);
674                 if (ret != LDB_SUCCESS) {
675                         talloc_free(msg);
676                         talloc_free(req);
677                         DEBUG(0, ("Autotransaction start failed\n"));
678                         return WERR_DS_DRA_INTERNAL_ERROR;
679                 }
680
681                 ret = ldb_request(ldb, req);
682                 if (ret == LDB_SUCCESS) {
683                         ret = ldb_wait(req->handle, LDB_WAIT_ALL);
684                 }
685
686                 if (ret == LDB_SUCCESS) {
687                         ret = ldb_transaction_commit(ldb);
688                 } else {
689                         DEBUG(0, ("Schema update now failed: %s\n", ldb_strerror(ret)));
690                         ldb_transaction_cancel(ldb);
691                 }
692
693                 talloc_free(msg);
694                 talloc_free(req);
695                 if (ret != LDB_SUCCESS) {
696                         DEBUG(0, ("Commit failed: %s\n", ldb_strerror(ret)));
697                         return WERR_DS_INTERNAL_FAILURE;
698                 }
699         }
700
701         DEBUG(2,("Replicated %u objects (%u linked attributes) for %s\n",
702                  objects->num_objects, objects->linked_attributes_count,
703                  ldb_dn_get_linearized(objects->partition_dn)));
704                  
705         return WERR_OK;
706 }
707
708 static WERROR dsdb_origin_object_convert(struct ldb_context *ldb,
709                                          const struct dsdb_schema *schema,
710                                          const struct drsuapi_DsReplicaObjectListItem *in,
711                                          TALLOC_CTX *mem_ctx,
712                                          struct ldb_message **_msg)
713 {
714         WERROR status;
715         unsigned int i;
716         struct ldb_message *msg;
717
718         if (!in->object.identifier) {
719                 return WERR_FOOBAR;
720         }
721
722         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
723                 return WERR_FOOBAR;
724         }
725
726         msg = ldb_msg_new(mem_ctx);
727         W_ERROR_HAVE_NO_MEMORY(msg);
728
729         msg->dn = ldb_dn_new(msg, ldb, in->object.identifier->dn);
730         W_ERROR_HAVE_NO_MEMORY(msg->dn);
731
732         msg->num_elements       = in->object.attribute_ctr.num_attributes;
733         msg->elements           = talloc_array(msg, struct ldb_message_element,
734                                                msg->num_elements);
735         W_ERROR_HAVE_NO_MEMORY(msg->elements);
736
737         for (i=0; i < msg->num_elements; i++) {
738                 struct drsuapi_DsReplicaAttribute *a;
739                 struct ldb_message_element *e;
740
741                 a = &in->object.attribute_ctr.attributes[i];
742                 e = &msg->elements[i];
743
744                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, schema->prefixmap,
745                                                        a, msg->elements, e);
746                 W_ERROR_NOT_OK_RETURN(status);
747         }
748
749
750         *_msg = msg;
751
752         return WERR_OK;
753 }
754
755 WERROR dsdb_origin_objects_commit(struct ldb_context *ldb,
756                                   TALLOC_CTX *mem_ctx,
757                                   const struct drsuapi_DsReplicaObjectListItem *first_object,
758                                   uint32_t *_num,
759                                   uint32_t dsdb_repl_flags,
760                                   struct drsuapi_DsReplicaObjectIdentifier2 **_ids)
761 {
762         WERROR status;
763         const struct dsdb_schema *schema;
764         const struct drsuapi_DsReplicaObjectListItem *cur;
765         struct ldb_message **objects;
766         struct drsuapi_DsReplicaObjectIdentifier2 *ids;
767         uint32_t i;
768         uint32_t num_objects = 0;
769         const char * const attrs[] = {
770                 "objectGUID",
771                 "objectSid",
772                 NULL
773         };
774         struct ldb_result *res;
775         int ret;
776
777         for (cur = first_object; cur; cur = cur->next_object) {
778                 num_objects++;
779         }
780
781         if (num_objects == 0) {
782                 return WERR_OK;
783         }
784
785         ret = ldb_transaction_start(ldb);
786         if (ret != LDB_SUCCESS) {
787                 return WERR_DS_INTERNAL_FAILURE;
788         }
789
790         objects = talloc_array(mem_ctx, struct ldb_message *,
791                                num_objects);
792         if (objects == NULL) {
793                 status = WERR_NOMEM;
794                 goto cancel;
795         }
796
797         schema = dsdb_get_schema(ldb, objects);
798         if (!schema) {
799                 return WERR_DS_SCHEMA_NOT_LOADED;
800         }
801
802         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
803                 status = dsdb_origin_object_convert(ldb, schema, cur,
804                                                     objects, &objects[i]);
805                 if (!W_ERROR_IS_OK(status)) {
806                         goto cancel;
807                 }
808         }
809
810         ids = talloc_array(mem_ctx,
811                            struct drsuapi_DsReplicaObjectIdentifier2,
812                            num_objects);
813         if (ids == NULL) {
814                 status = WERR_NOMEM;
815                 goto cancel;
816         }
817
818         if (dsdb_repl_flags & DSDB_REPL_FLAG_ADD_NCNAME) {
819                 /* check for possible NC creation */
820                 for (i=0; i < num_objects; i++) {
821                         struct ldb_message *msg = objects[i];
822                         struct ldb_message_element *el;
823                         struct ldb_dn *nc_dn;
824
825                         if (ldb_msg_check_string_attribute(msg, "objectClass", "crossRef") == 0) {
826                                 continue;
827                         }
828                         el = ldb_msg_find_element(msg, "nCName");
829                         if (el == NULL || el->num_values != 1) {
830                                 continue;
831                         }
832                         nc_dn = ldb_dn_from_ldb_val(objects, ldb, &el->values[0]);
833                         if (!ldb_dn_validate(nc_dn)) {
834                                 continue;
835                         }
836                         ret = dsdb_create_partial_replica_NC(ldb, nc_dn);
837                         if (ret != LDB_SUCCESS) {
838                                 status = WERR_DS_INTERNAL_FAILURE;
839                                 goto cancel;
840                         }
841                 }
842         }
843
844         for (i=0; i < num_objects; i++) {
845                 struct dom_sid *sid = NULL;
846                 struct ldb_request *add_req;
847
848                 DEBUG(6,(__location__ ": adding %s\n", 
849                          ldb_dn_get_linearized(objects[i]->dn)));
850
851                 ret = ldb_build_add_req(&add_req,
852                                         ldb,
853                                         objects,
854                                         objects[i],
855                                         NULL,
856                                         NULL,
857                                         ldb_op_default_callback,
858                                         NULL);
859                 if (ret != LDB_SUCCESS) {
860                         status = WERR_DS_INTERNAL_FAILURE;
861                         goto cancel;
862                 }
863
864                 ret = ldb_request_add_control(add_req, LDB_CONTROL_RELAX_OID, true, NULL);
865                 if (ret != LDB_SUCCESS) {
866                         status = WERR_DS_INTERNAL_FAILURE;
867                         goto cancel;
868                 }
869                 
870                 ret = ldb_request(ldb, add_req);
871                 if (ret == LDB_SUCCESS) {
872                         ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
873                 }
874                 if (ret != LDB_SUCCESS) {
875                         DEBUG(0,(__location__ ": Failed add of %s - %s\n",
876                                  ldb_dn_get_linearized(objects[i]->dn), ldb_errstring(ldb)));
877                         status = WERR_DS_INTERNAL_FAILURE;
878                         goto cancel;
879                 }
880
881                 talloc_free(add_req);
882
883                 ret = ldb_search(ldb, objects, &res, objects[i]->dn,
884                                  LDB_SCOPE_BASE, attrs,
885                                  "(objectClass=*)");
886                 if (ret != LDB_SUCCESS) {
887                         status = WERR_DS_INTERNAL_FAILURE;
888                         goto cancel;
889                 }
890                 ids[i].guid = samdb_result_guid(res->msgs[0], "objectGUID");
891                 sid = samdb_result_dom_sid(objects, res->msgs[0], "objectSid");
892                 if (sid) {
893                         ids[i].sid = *sid;
894                 } else {
895                         ZERO_STRUCT(ids[i].sid);
896                 }
897         }
898
899         ret = ldb_transaction_commit(ldb);
900         if (ret != LDB_SUCCESS) {
901                 return WERR_DS_INTERNAL_FAILURE;
902         }
903
904         talloc_free(objects);
905
906         *_num = num_objects;
907         *_ids = ids;
908         return WERR_OK;
909
910 cancel:
911         talloc_free(objects);
912         ldb_transaction_cancel(ldb);
913         return status;
914 }