bbfcfd8660b8ffbb6d7b3f494c79ecbcdc1ff7a9
[kamenim/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
65         /* make a copy of the iniatial_scheam so we don't mess with it */
66         working_schema = dsdb_schema_copy_shallow(mem_ctx, ldb, initial_schema);
67         if (!working_schema) {
68                 DEBUG(0,(__location__ ": schema copy failed!\n"));
69                 return WERR_NOMEM;
70         }
71
72         /* we are going to need remote prefixMap for decoding */
73         werr = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
74                                                 mem_ctx, &pfm_remote, NULL);
75         if (!W_ERROR_IS_OK(werr)) {
76                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
77                          win_errstr(werr)));
78                 return werr;
79         }
80
81         /* create a list of objects yet to be converted */
82         for (cur = first_object; cur; cur = cur->next_object) {
83                 schema_list_item = talloc(mem_ctx, struct schema_list);
84                 schema_list_item->obj = cur;
85                 DLIST_ADD_END(schema_list, schema_list_item, struct schema_list);
86         }
87
88         /* resolve objects until all are resolved and in local schema */
89         pass_no = 1;
90
91         while (schema_list) {
92                 uint32_t converted_obj_count = 0;
93                 uint32_t failed_obj_count = 0;
94                 TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
95                 W_ERROR_HAVE_NO_MEMORY(tmp_ctx);
96
97                 for (schema_list_item = schema_list; schema_list_item; schema_list_item=schema_list_next_item) {
98                         struct dsdb_extended_replicated_object object;
99
100                         cur = schema_list_item->obj;
101
102                         /* Save the next item, now we have saved out
103                          * the current one, so we can DLIST_REMOVE it
104                          * safely */
105                         schema_list_next_item = schema_list_item->next;
106
107                         /*
108                          * Convert the objects into LDB messages using the
109                          * schema we have so far. It's ok if we fail to convert
110                          * an object. We should convert more objects on next pass.
111                          */
112                         werr = dsdb_convert_object_ex(ldb, working_schema, pfm_remote,
113                                                       cur, gensec_skey,
114                                                       tmp_ctx, &object);
115                         if (!W_ERROR_IS_OK(werr)) {
116                                 DEBUG(1,("Warning: Failed to convert schema object %s into ldb msg\n",
117                                          cur->object.identifier->dn));
118
119                                 failed_obj_count++;
120                         } else {
121                                 /*
122                                  * Convert the schema from ldb_message format
123                                  * (OIDs as OID strings) into schema, using
124                                  * the remote prefixMap
125                                  */
126                                 werr = dsdb_schema_set_el_from_ldb_msg(ldb,
127                                                                        working_schema,
128                                                                        object.msg);
129                                 if (!W_ERROR_IS_OK(werr)) {
130                                         DEBUG(1,("Warning: failed to convert object %s into a schema element: %s\n",
131                                                  ldb_dn_get_linearized(object.msg->dn),
132                                                  win_errstr(werr)));
133                                         failed_obj_count++;
134                                 } else {
135                                         DLIST_REMOVE(schema_list, schema_list_item);
136                                         talloc_free(schema_list_item);
137                                         converted_obj_count++;
138                                 }
139                         }
140                 }
141                 talloc_free(tmp_ctx);
142
143                 DEBUG(4,("Schema load pass %d: %d/%d of %d objects left to be converted.\n",
144                          pass_no, failed_obj_count, converted_obj_count, object_count));
145                 pass_no++;
146
147                 /* check if we converted any objects in this pass */
148                 if (converted_obj_count == 0) {
149                         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));
150                         return WERR_INTERNAL_ERROR;
151                 }
152
153                 /* rebuild indexes */
154                 ret = dsdb_setup_sorted_accessors(ldb, working_schema);
155                 if (LDB_SUCCESS != ret) {
156                         DEBUG(0,("Failed to create schema-cache indexes!\n"));
157                         return WERR_INTERNAL_ERROR;
158                 }
159         };
160
161         *_schema_out = working_schema;
162
163         return WERR_OK;
164 }
165
166 WERROR dsdb_convert_object_ex(struct ldb_context *ldb,
167                               const struct dsdb_schema *schema,
168                               const struct dsdb_schema_prefixmap *pfm_remote,
169                               const struct drsuapi_DsReplicaObjectListItemEx *in,
170                               const DATA_BLOB *gensec_skey,
171                               TALLOC_CTX *mem_ctx,
172                               struct dsdb_extended_replicated_object *out)
173 {
174         NTSTATUS nt_status;
175         WERROR status;
176         uint32_t i;
177         struct ldb_message *msg;
178         struct replPropertyMetaDataBlob *md;
179         struct ldb_val guid_value;
180         NTTIME whenChanged = 0;
181         time_t whenChanged_t;
182         const char *whenChanged_s;
183         const char *rdn_name = NULL;
184         const struct ldb_val *rdn_value = NULL;
185         const struct dsdb_attribute *rdn_attr = NULL;
186         uint32_t rdn_attid;
187         struct drsuapi_DsReplicaAttribute *name_a = NULL;
188         struct drsuapi_DsReplicaMetaData *name_d = NULL;
189         struct replPropertyMetaData1 *rdn_m = NULL;
190         struct dom_sid *sid = NULL;
191         uint32_t rid = 0;
192         int ret;
193
194         if (!in->object.identifier) {
195                 return WERR_FOOBAR;
196         }
197
198         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
199                 return WERR_FOOBAR;
200         }
201
202         if (in->object.attribute_ctr.num_attributes != 0 && !in->meta_data_ctr) {
203                 return WERR_FOOBAR;
204         }
205
206         if (in->object.attribute_ctr.num_attributes != in->meta_data_ctr->count) {
207                 return WERR_FOOBAR;
208         }
209
210         sid = &in->object.identifier->sid;
211         if (sid->num_auths > 0) {
212                 rid = sid->sub_auths[sid->num_auths - 1];
213         }
214
215         msg = ldb_msg_new(mem_ctx);
216         W_ERROR_HAVE_NO_MEMORY(msg);
217
218         msg->dn                 = ldb_dn_new(msg, ldb, in->object.identifier->dn);
219         W_ERROR_HAVE_NO_MEMORY(msg->dn);
220
221         rdn_name        = ldb_dn_get_rdn_name(msg->dn);
222         rdn_attr        = dsdb_attribute_by_lDAPDisplayName(schema, rdn_name);
223         if (!rdn_attr) {
224                 return WERR_FOOBAR;
225         }
226         rdn_attid       = rdn_attr->attributeID_id;
227         rdn_value       = ldb_dn_get_rdn_val(msg->dn);
228
229         msg->num_elements       = in->object.attribute_ctr.num_attributes;
230         msg->elements           = talloc_array(msg, struct ldb_message_element,
231                                                msg->num_elements);
232         W_ERROR_HAVE_NO_MEMORY(msg->elements);
233
234         md = talloc(mem_ctx, struct replPropertyMetaDataBlob);
235         W_ERROR_HAVE_NO_MEMORY(md);
236
237         md->version             = 1;
238         md->reserved            = 0;
239         md->ctr.ctr1.count      = in->meta_data_ctr->count;
240         md->ctr.ctr1.reserved   = 0;
241         md->ctr.ctr1.array      = talloc_array(mem_ctx,
242                                                struct replPropertyMetaData1,
243                                                md->ctr.ctr1.count + 1); /* +1 because of the RDN attribute */
244         W_ERROR_HAVE_NO_MEMORY(md->ctr.ctr1.array);
245
246         for (i=0; i < in->meta_data_ctr->count; i++) {
247                 struct drsuapi_DsReplicaAttribute *a;
248                 struct drsuapi_DsReplicaMetaData *d;
249                 struct replPropertyMetaData1 *m;
250                 struct ldb_message_element *e;
251                 uint32_t j;
252
253                 a = &in->object.attribute_ctr.attributes[i];
254                 d = &in->meta_data_ctr->meta_data[i];
255                 m = &md->ctr.ctr1.array[i];
256                 e = &msg->elements[i];
257
258                 for (j=0; j<a->value_ctr.num_values; j++) {
259                         status = drsuapi_decrypt_attribute(a->value_ctr.values[j].blob, gensec_skey, rid, a);
260                         W_ERROR_NOT_OK_RETURN(status);
261                 }
262
263                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, pfm_remote,
264                                                        a, msg->elements, e);
265                 W_ERROR_NOT_OK_RETURN(status);
266
267                 m->attid                        = a->attid;
268                 m->version                      = d->version;
269                 m->originating_change_time      = d->originating_change_time;
270                 m->originating_invocation_id    = d->originating_invocation_id;
271                 m->originating_usn              = d->originating_usn;
272                 m->local_usn                    = 0;
273
274                 if (d->originating_change_time > whenChanged) {
275                         whenChanged = d->originating_change_time;
276                 }
277
278                 if (a->attid == DRSUAPI_ATTID_name) {
279                         name_a = a;
280                         name_d = d;
281                         rdn_m = &md->ctr.ctr1.array[md->ctr.ctr1.count];
282                 }
283         }
284
285         if (rdn_m) {
286                 struct ldb_message_element *el;
287                 el = ldb_msg_find_element(msg, rdn_attr->lDAPDisplayName);
288                 if (!el) {
289                         ret = ldb_msg_add_value(msg, rdn_attr->lDAPDisplayName, rdn_value, NULL);
290                         if (ret != LDB_SUCCESS) {
291                                 return WERR_FOOBAR;
292                         }
293                 } else {
294                         if (el->num_values != 1) {
295                                 DEBUG(0,(__location__ ": Unexpected num_values=%u\n",
296                                          el->num_values));
297                                 return WERR_FOOBAR;                             
298                         }
299                         if (!ldb_val_equal_exact(&el->values[0], rdn_value)) {
300                                 DEBUG(0,(__location__ ": RDN value changed? '%*.*s' '%*.*s'\n",
301                                          (int)el->values[0].length, (int)el->values[0].length, el->values[0].data,
302                                          (int)rdn_value->length, (int)rdn_value->length, rdn_value->data));
303                                 return WERR_FOOBAR;                             
304                         }
305                 }
306
307                 rdn_m->attid                            = rdn_attid;
308                 rdn_m->version                          = name_d->version;
309                 rdn_m->originating_change_time          = name_d->originating_change_time;
310                 rdn_m->originating_invocation_id        = name_d->originating_invocation_id;
311                 rdn_m->originating_usn                  = name_d->originating_usn;
312                 rdn_m->local_usn                        = 0;
313                 md->ctr.ctr1.count++;
314
315         }
316
317         whenChanged_t = nt_time_to_unix(whenChanged);
318         whenChanged_s = ldb_timestring(msg, whenChanged_t);
319         W_ERROR_HAVE_NO_MEMORY(whenChanged_s);
320
321         nt_status = GUID_to_ndr_blob(&in->object.identifier->guid, msg, &guid_value);
322         if (!NT_STATUS_IS_OK(nt_status)) {
323                 return ntstatus_to_werror(nt_status);
324         }
325
326         out->msg                = msg;
327         out->guid_value         = guid_value;
328         out->when_changed       = whenChanged_s;
329         out->meta_data          = md;
330         return WERR_OK;
331 }
332
333 WERROR dsdb_replicated_objects_convert(struct ldb_context *ldb,
334                                        const struct dsdb_schema *schema,
335                                        const char *partition_dn_str,
336                                        const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr,
337                                        uint32_t object_count,
338                                        const struct drsuapi_DsReplicaObjectListItemEx *first_object,
339                                        uint32_t linked_attributes_count,
340                                        const struct drsuapi_DsReplicaLinkedAttribute *linked_attributes,
341                                        const struct repsFromTo1 *source_dsa,
342                                        const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector,
343                                        const DATA_BLOB *gensec_skey,
344                                        TALLOC_CTX *mem_ctx,
345                                        struct dsdb_extended_replicated_objects **objects)
346 {
347         WERROR status;
348         struct ldb_dn *partition_dn;
349         struct dsdb_schema_prefixmap *pfm_remote;
350         struct dsdb_extended_replicated_objects *out;
351         const struct drsuapi_DsReplicaObjectListItemEx *cur;
352         uint32_t i;
353
354         out = talloc_zero(mem_ctx, struct dsdb_extended_replicated_objects);
355         W_ERROR_HAVE_NO_MEMORY(out);
356         out->version            = DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION;
357
358         /*
359          * Ensure schema is kept valid for as long as 'out'
360          * which may contain pointers to it
361          */
362         schema = talloc_reference(out, schema);
363         W_ERROR_HAVE_NO_MEMORY(schema);
364
365         partition_dn = ldb_dn_new(out, ldb, partition_dn_str);
366         W_ERROR_HAVE_NO_MEMORY_AND_FREE(partition_dn, out);
367
368         status = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
369                                                   out, &pfm_remote, NULL);
370         if (!W_ERROR_IS_OK(status)) {
371                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
372                          win_errstr(status)));
373                 talloc_free(out);
374                 return status;
375         }
376
377         if (ldb_dn_compare(partition_dn, ldb_get_schema_basedn(ldb)) != 0) {
378                 /*
379                  * check for schema changes in case
380                  * we are not replicating Schema NC
381                  */
382                 status = dsdb_schema_info_cmp(schema, mapping_ctr);
383                 if (!W_ERROR_IS_OK(status)) {
384                         DEBUG(1,("Remote schema has changed while replicating %s\n",
385                                  partition_dn_str));
386                         talloc_free(out);
387                         return status;
388                 }
389         }
390
391         out->partition_dn       = partition_dn;
392
393         out->source_dsa         = source_dsa;
394         out->uptodateness_vector= uptodateness_vector;
395
396         out->num_objects        = object_count;
397         out->objects            = talloc_array(out,
398                                                struct dsdb_extended_replicated_object,
399                                                out->num_objects);
400         W_ERROR_HAVE_NO_MEMORY_AND_FREE(out->objects, out);
401
402         /* pass the linked attributes down to the repl_meta_data
403            module */
404         out->linked_attributes_count = linked_attributes_count;
405         out->linked_attributes       = linked_attributes;
406
407         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
408                 if (i == out->num_objects) {
409                         talloc_free(out);
410                         return WERR_FOOBAR;
411                 }
412
413                 status = dsdb_convert_object_ex(ldb, schema, pfm_remote,
414                                                 cur, gensec_skey,
415                                                 out->objects, &out->objects[i]);
416                 if (!W_ERROR_IS_OK(status)) {
417                         talloc_free(out);
418                         DEBUG(0,("Failed to convert object %s: %s\n",
419                                  cur->object.identifier->dn,
420                                  win_errstr(status)));
421                         return status;
422                 }
423         }
424         if (i != out->num_objects) {
425                 talloc_free(out);
426                 return WERR_FOOBAR;
427         }
428
429         /* free pfm_remote, we won't need it anymore */
430         talloc_free(pfm_remote);
431
432         *objects = out;
433         return WERR_OK;
434 }
435
436 /**
437  * Commits a list of replicated objects.
438  *
439  * @param working_schema dsdb_schema to be used for resolving
440  *                       Classes/Attributes during Schema replication. If not NULL,
441  *                       it will be set on ldb and used while committing replicated objects
442  */
443 WERROR dsdb_replicated_objects_commit(struct ldb_context *ldb,
444                                       struct dsdb_schema *working_schema,
445                                       struct dsdb_extended_replicated_objects *objects,
446                                       uint64_t *notify_uSN)
447 {
448         WERROR werr;
449         struct ldb_result *ext_res;
450         struct dsdb_schema *cur_schema = NULL;
451         int ret;
452         uint64_t seq_num1, seq_num2;
453
454         /* TODO: handle linked attributes */
455
456         /* wrap the extended operation in a transaction 
457            See [MS-DRSR] 3.3.2 Transactions
458          */
459         ret = ldb_transaction_start(ldb);
460         if (ret != LDB_SUCCESS) {
461                 DEBUG(0,(__location__ " Failed to start transaction\n"));
462                 return WERR_FOOBAR;
463         }
464
465         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num1, NULL);
466         if (ret != LDB_SUCCESS) {
467                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
468                 ldb_transaction_cancel(ldb);
469                 return WERR_FOOBAR;             
470         }
471
472         /*
473          * Set working_schema for ldb in case we are replicating from Schema NC.
474          * Schema won't be reloaded during Replicated Objects commit, as it is
475          * done in a transaction. So we need some way to search for newly
476          * added Classes and Attributes
477          */
478         if (working_schema) {
479                 /* store current schema so we can fall back in case of failure */
480                 cur_schema = dsdb_get_schema(ldb, working_schema);
481
482                 ret = dsdb_reference_schema(ldb, working_schema, false);
483                 if (ret != LDB_SUCCESS) {
484                         DEBUG(0,(__location__ "Failed to reference working schema - %s\n",
485                                  ldb_strerror(ret)));
486                         /* TODO: Map LDB Error to NTSTATUS? */
487                         ldb_transaction_cancel(ldb);
488                         return WERR_INTERNAL_ERROR;
489                 }
490         }
491
492         ret = ldb_extended(ldb, DSDB_EXTENDED_REPLICATED_OBJECTS_OID, objects, &ext_res);
493         if (ret != LDB_SUCCESS) {
494                 /* restore previous schema */
495                 if (cur_schema ) {
496                         dsdb_reference_schema(ldb, cur_schema, false);
497                         dsdb_make_schema_global(ldb, cur_schema);
498                 }
499
500                 DEBUG(0,("Failed to apply records: %s: %s\n",
501                          ldb_errstring(ldb), ldb_strerror(ret)));
502                 ldb_transaction_cancel(ldb);
503                 return WERR_FOOBAR;
504         }
505         talloc_free(ext_res);
506
507         /* Save our updated prefixMap */
508         if (working_schema) {
509                 werr = dsdb_write_prefixes_from_schema_to_ldb(working_schema,
510                                                               ldb,
511                                                               working_schema);
512                 if (!W_ERROR_IS_OK(werr)) {
513                         /* restore previous schema */
514                         if (cur_schema ) {
515                                 dsdb_reference_schema(ldb, cur_schema, false);
516                                 dsdb_make_schema_global(ldb, cur_schema);
517                         }
518                         DEBUG(0,("Failed to save updated prefixMap: %s\n",
519                                  win_errstr(werr)));
520                         return werr;
521                 }
522         }
523
524         ret = ldb_transaction_prepare_commit(ldb);
525         if (ret != LDB_SUCCESS) {
526                 /* restore previous schema */
527                 if (cur_schema ) {
528                         dsdb_reference_schema(ldb, cur_schema, false);
529                         dsdb_make_schema_global(ldb, cur_schema);
530                 }
531                 DEBUG(0,(__location__ " Failed to prepare commit of transaction: %s\n",
532                          ldb_errstring(ldb)));
533                 return WERR_FOOBAR;
534         }
535
536         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num2, NULL);
537         if (ret != LDB_SUCCESS) {
538                 /* restore previous schema */
539                 if (cur_schema ) {
540                         dsdb_reference_schema(ldb, cur_schema, false);
541                         dsdb_make_schema_global(ldb, cur_schema);
542                 }
543                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
544                 ldb_transaction_cancel(ldb);
545                 return WERR_FOOBAR;             
546         }
547
548         /* if this replication partner didn't need to be notified
549            before this transaction then it still doesn't need to be
550            notified, as the changes came from this server */    
551         if (seq_num2 > seq_num1 && seq_num1 <= *notify_uSN) {
552                 *notify_uSN = seq_num2;
553         }
554
555         ret = ldb_transaction_commit(ldb);
556         if (ret != LDB_SUCCESS) {
557                 /* restore previous schema */
558                 if (cur_schema ) {
559                         dsdb_reference_schema(ldb, cur_schema, false);
560                         dsdb_make_schema_global(ldb, cur_schema);
561                 }
562                 DEBUG(0,(__location__ " Failed to commit transaction\n"));
563                 return WERR_FOOBAR;
564         }
565
566         /*
567          * Reset the Schema used by ldb. This will lead to
568          * a schema cache being refreshed from database.
569          */
570         if (working_schema) {
571                 cur_schema = dsdb_get_schema(ldb, NULL);
572                 /* TODO: What we do in case dsdb_get_schema() fail?
573                  *       We can't fallback at this point anymore */
574                 if (cur_schema) {
575                         dsdb_make_schema_global(ldb, cur_schema);
576                 }
577         }
578
579         DEBUG(2,("Replicated %u objects (%u linked attributes) for %s\n",
580                  objects->num_objects, objects->linked_attributes_count,
581                  ldb_dn_get_linearized(objects->partition_dn)));
582                  
583         return WERR_OK;
584 }
585
586 static WERROR dsdb_origin_object_convert(struct ldb_context *ldb,
587                                          const struct dsdb_schema *schema,
588                                          const struct drsuapi_DsReplicaObjectListItem *in,
589                                          TALLOC_CTX *mem_ctx,
590                                          struct ldb_message **_msg)
591 {
592         WERROR status;
593         unsigned int i;
594         struct ldb_message *msg;
595
596         if (!in->object.identifier) {
597                 return WERR_FOOBAR;
598         }
599
600         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
601                 return WERR_FOOBAR;
602         }
603
604         msg = ldb_msg_new(mem_ctx);
605         W_ERROR_HAVE_NO_MEMORY(msg);
606
607         msg->dn = ldb_dn_new(msg, ldb, in->object.identifier->dn);
608         W_ERROR_HAVE_NO_MEMORY(msg->dn);
609
610         msg->num_elements       = in->object.attribute_ctr.num_attributes;
611         msg->elements           = talloc_array(msg, struct ldb_message_element,
612                                                msg->num_elements);
613         W_ERROR_HAVE_NO_MEMORY(msg->elements);
614
615         for (i=0; i < msg->num_elements; i++) {
616                 struct drsuapi_DsReplicaAttribute *a;
617                 struct ldb_message_element *e;
618
619                 a = &in->object.attribute_ctr.attributes[i];
620                 e = &msg->elements[i];
621
622                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, schema->prefixmap,
623                                                        a, msg->elements, e);
624                 W_ERROR_NOT_OK_RETURN(status);
625         }
626
627
628         *_msg = msg;
629
630         return WERR_OK;
631 }
632
633 WERROR dsdb_origin_objects_commit(struct ldb_context *ldb,
634                                   TALLOC_CTX *mem_ctx,
635                                   const struct drsuapi_DsReplicaObjectListItem *first_object,
636                                   uint32_t *_num,
637                                   struct drsuapi_DsReplicaObjectIdentifier2 **_ids)
638 {
639         WERROR status;
640         const struct dsdb_schema *schema;
641         const struct drsuapi_DsReplicaObjectListItem *cur;
642         struct ldb_message **objects;
643         struct drsuapi_DsReplicaObjectIdentifier2 *ids;
644         uint32_t i;
645         uint32_t num_objects = 0;
646         const char * const attrs[] = {
647                 "objectGUID",
648                 "objectSid",
649                 NULL
650         };
651         struct ldb_result *res;
652         int ret;
653
654         for (cur = first_object; cur; cur = cur->next_object) {
655                 num_objects++;
656         }
657
658         if (num_objects == 0) {
659                 return WERR_OK;
660         }
661
662         ret = ldb_transaction_start(ldb);
663         if (ret != LDB_SUCCESS) {
664                 return WERR_DS_INTERNAL_FAILURE;
665         }
666
667         objects = talloc_array(mem_ctx, struct ldb_message *,
668                                num_objects);
669         if (objects == NULL) {
670                 status = WERR_NOMEM;
671                 goto cancel;
672         }
673
674         schema = dsdb_get_schema(ldb, objects);
675         if (!schema) {
676                 return WERR_DS_SCHEMA_NOT_LOADED;
677         }
678
679         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
680                 status = dsdb_origin_object_convert(ldb, schema, cur,
681                                                     objects, &objects[i]);
682                 if (!W_ERROR_IS_OK(status)) {
683                         goto cancel;
684                 }
685         }
686
687         ids = talloc_array(mem_ctx,
688                            struct drsuapi_DsReplicaObjectIdentifier2,
689                            num_objects);
690         if (ids == NULL) {
691                 status = WERR_NOMEM;
692                 goto cancel;
693         }
694
695         for (i=0; i < num_objects; i++) {
696                 struct dom_sid *sid = NULL;
697                 struct ldb_request *add_req;
698
699                 DEBUG(6,(__location__ ": adding %s\n", 
700                          ldb_dn_get_linearized(objects[i]->dn)));
701
702                 ret = ldb_build_add_req(&add_req,
703                                         ldb,
704                                         objects,
705                                         objects[i],
706                                         NULL,
707                                         NULL,
708                                         ldb_op_default_callback,
709                                         NULL);
710                 if (ret != LDB_SUCCESS) {
711                         status = WERR_DS_INTERNAL_FAILURE;
712                         goto cancel;
713                 }
714
715                 ret = ldb_request_add_control(add_req, LDB_CONTROL_RELAX_OID, true, NULL);
716                 if (ret != LDB_SUCCESS) {
717                         status = WERR_DS_INTERNAL_FAILURE;
718                         goto cancel;
719                 }
720                 
721                 ret = ldb_request(ldb, add_req);
722                 if (ret == LDB_SUCCESS) {
723                         ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
724                 }
725                 if (ret != LDB_SUCCESS) {
726                         DEBUG(0,(__location__ ": Failed add of %s - %s\n",
727                                  ldb_dn_get_linearized(objects[i]->dn), ldb_errstring(ldb)));
728                         status = WERR_DS_INTERNAL_FAILURE;
729                         goto cancel;
730                 }
731
732                 talloc_free(add_req);
733
734                 ret = ldb_search(ldb, objects, &res, objects[i]->dn,
735                                  LDB_SCOPE_BASE, attrs,
736                                  "(objectClass=*)");
737                 if (ret != LDB_SUCCESS) {
738                         status = WERR_DS_INTERNAL_FAILURE;
739                         goto cancel;
740                 }
741                 ids[i].guid = samdb_result_guid(res->msgs[0], "objectGUID");
742                 sid = samdb_result_dom_sid(objects, res->msgs[0], "objectSid");
743                 if (sid) {
744                         ids[i].sid = *sid;
745                 } else {
746                         ZERO_STRUCT(ids[i].sid);
747                 }
748         }
749
750         ret = ldb_transaction_commit(ldb);
751         if (ret != LDB_SUCCESS) {
752                 return WERR_DS_INTERNAL_FAILURE;
753         }
754
755         talloc_free(objects);
756
757         *_num = num_objects;
758         *_ids = ids;
759         return WERR_OK;
760
761 cancel:
762         talloc_free(objects);
763         ldb_transaction_cancel(ldb);
764         return status;
765 }