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