s4-drs: replmd_delete with the 3 stage deletion recycle bin
[nivanova/samba-autobuild/.git] / source4 / dsdb / samdb / ldb_modules / repl_meta_data.c
1 /* 
2    ldb database library
3
4    Copyright (C) Simo Sorce  2004-2008
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  *  Name: ldb
25  *
26  *  Component: ldb repl_meta_data module
27  *
28  *  Description: - add a unique objectGUID onto every new record,
29  *               - handle whenCreated, whenChanged timestamps
30  *               - handle uSNCreated, uSNChanged numbers
31  *               - handle replPropertyMetaData attribute
32  *
33  *  Author: Simo Sorce
34  *  Author: Stefan Metzmacher
35  */
36
37 #include "includes.h"
38 #include "ldb_module.h"
39 #include "dsdb/samdb/samdb.h"
40 #include "dsdb/common/proto.h"
41 #include "../libds/common/flags.h"
42 #include "librpc/gen_ndr/ndr_misc.h"
43 #include "librpc/gen_ndr/ndr_drsuapi.h"
44 #include "librpc/gen_ndr/ndr_drsblobs.h"
45 #include "param/param.h"
46 #include "libcli/security/dom_sid.h"
47 #include "lib/util/dlinklist.h"
48 #include "dsdb/samdb/ldb_modules/util.h"
49 #include "lib/util/binsearch.h"
50 #include "libcli/security/security.h"
51 #include "lib/util/tsort.h"
52
53 #define W2K3_LINKED_ATTRIBUTES 1
54
55 struct replmd_private {
56         TALLOC_CTX *la_ctx;
57         struct la_entry *la_list;
58         TALLOC_CTX *bl_ctx;
59         struct la_backlink *la_backlinks;
60         struct nc_entry {
61                 struct nc_entry *prev, *next;
62                 struct ldb_dn *dn;
63                 uint64_t mod_usn;
64                 uint64_t mod_usn_urgent;
65         } *ncs;
66 };
67
68 struct la_entry {
69         struct la_entry *next, *prev;
70         struct drsuapi_DsReplicaLinkedAttribute *la;
71 };
72
73 struct replmd_replicated_request {
74         struct ldb_module *module;
75         struct ldb_request *req;
76
77         const struct dsdb_schema *schema;
78
79         /* the controls we pass down */
80         struct ldb_control **controls;
81
82         /* details for the mode where we apply a bunch of inbound replication meessages */
83         bool apply_mode;
84         uint32_t index_current;
85         struct dsdb_extended_replicated_objects *objs;
86
87         struct ldb_message *search_msg;
88
89         uint64_t seq_num;
90         bool is_urgent;
91 };
92
93 enum urgent_situation {
94         REPL_URGENT_ON_CREATE = 1,
95         REPL_URGENT_ON_UPDATE = 2,
96         REPL_URGENT_ON_DELETE = 4
97 };
98
99
100 static const struct {
101         const char *update_name;
102         enum urgent_situation repl_situation;
103 } urgent_objects[] = {
104                 {"nTDSDSA", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_DELETE)},
105                 {"crossRef", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_DELETE)},
106                 {"attributeSchema", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_UPDATE)},
107                 {"classSchema", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_UPDATE)},
108                 {"secret", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_UPDATE)},
109                 {"rIDManager", (REPL_URGENT_ON_CREATE | REPL_URGENT_ON_UPDATE)},
110                 {NULL, 0}
111 };
112
113 /* Attributes looked for when updating or deleting, to check for a urgent replication needed */
114 static const char *urgent_attrs[] = {
115                 "lockoutTime",
116                 "pwdLastSet",
117                 "userAccountControl",
118                 NULL
119 };
120
121
122 static bool replmd_check_urgent_objectclass(const struct ldb_message_element *objectclass_el,
123                                         enum urgent_situation situation)
124 {
125         int i, j;
126         for (i=0; urgent_objects[i].update_name; i++) {
127
128                 if ((situation & urgent_objects[i].repl_situation) == 0) {
129                         continue;
130                 }
131
132                 for (j=0; j<objectclass_el->num_values; j++) {
133                         const struct ldb_val *v = &objectclass_el->values[j];
134                         if (ldb_attr_cmp((const char *)v->data, urgent_objects[i].update_name) == 0) {
135                                 return true;
136                         }
137                 }
138         }
139         return false;
140 }
141
142 static bool replmd_check_urgent_attribute(const struct ldb_message_element *el)
143 {
144         if (ldb_attr_in_list(urgent_attrs, el->name)) {
145                 return true;
146         }
147         return false;
148 }
149
150
151 static int replmd_replicated_apply_next(struct replmd_replicated_request *ar);
152
153 /*
154   initialise the module
155   allocate the private structure and build the list
156   of partition DNs for use by replmd_notify()
157  */
158 static int replmd_init(struct ldb_module *module)
159 {
160         struct replmd_private *replmd_private;
161         struct ldb_context *ldb = ldb_module_get_ctx(module);
162
163         replmd_private = talloc_zero(module, struct replmd_private);
164         if (replmd_private == NULL) {
165                 ldb_oom(ldb);
166                 return LDB_ERR_OPERATIONS_ERROR;
167         }
168         ldb_module_set_private(module, replmd_private);
169
170         return ldb_next_init(module);
171 }
172
173 /*
174   cleanup our per-transaction contexts
175  */
176 static void replmd_txn_cleanup(struct replmd_private *replmd_private)
177 {
178         talloc_free(replmd_private->la_ctx);
179         replmd_private->la_list = NULL;
180         replmd_private->la_ctx = NULL;
181
182         talloc_free(replmd_private->bl_ctx);
183         replmd_private->la_backlinks = NULL;
184         replmd_private->bl_ctx = NULL;
185 }
186
187
188 struct la_backlink {
189         struct la_backlink *next, *prev;
190         const char *attr_name;
191         struct GUID forward_guid, target_guid;
192         bool active;
193 };
194
195 /*
196   process a backlinks we accumulated during a transaction, adding and
197   deleting the backlinks from the target objects
198  */
199 static int replmd_process_backlink(struct ldb_module *module, struct la_backlink *bl)
200 {
201         struct ldb_dn *target_dn, *source_dn;
202         int ret;
203         struct ldb_context *ldb = ldb_module_get_ctx(module);
204         struct ldb_message *msg;
205         TALLOC_CTX *tmp_ctx = talloc_new(bl);
206         char *dn_string;
207
208         /*
209           - find DN of target
210           - find DN of source
211           - construct ldb_message
212               - either an add or a delete
213          */
214         ret = dsdb_module_dn_by_guid(module, tmp_ctx, &bl->target_guid, &target_dn);
215         if (ret != LDB_SUCCESS) {
216                 ldb_asprintf_errstring(ldb, "Failed to find target DN for linked attribute with GUID %s\n",
217                                        GUID_string(bl, &bl->target_guid));
218                 talloc_free(tmp_ctx);
219                 return ret;
220         }
221
222         ret = dsdb_module_dn_by_guid(module, tmp_ctx, &bl->forward_guid, &source_dn);
223         if (ret != LDB_SUCCESS) {
224                 ldb_asprintf_errstring(ldb, "Failed to find source DN for linked attribute with GUID %s\n",
225                                        GUID_string(bl, &bl->forward_guid));
226                 talloc_free(tmp_ctx);
227                 return ret;
228         }
229
230         msg = ldb_msg_new(tmp_ctx);
231         if (msg == NULL) {
232                 ldb_module_oom(module);
233                 talloc_free(tmp_ctx);
234                 return LDB_ERR_OPERATIONS_ERROR;
235         }
236
237         /* construct a ldb_message for adding/deleting the backlink */
238         msg->dn = target_dn;
239         dn_string = ldb_dn_get_extended_linearized(tmp_ctx, source_dn, 1);
240         if (!dn_string) {
241                 ldb_module_oom(module);
242                 talloc_free(tmp_ctx);
243                 return LDB_ERR_OPERATIONS_ERROR;
244         }
245         ret = ldb_msg_add_steal_string(msg, bl->attr_name, dn_string);
246         if (ret != LDB_SUCCESS) {
247                 talloc_free(tmp_ctx);
248                 return ret;
249         }
250         msg->elements[0].flags = bl->active?LDB_FLAG_MOD_ADD:LDB_FLAG_MOD_DELETE;
251
252         ret = dsdb_module_modify(module, msg, 0);
253         if (ret != LDB_SUCCESS) {
254                 ldb_asprintf_errstring(ldb, "Failed to %s backlink from %s to %s - %s",
255                                        bl->active?"add":"remove",
256                                        ldb_dn_get_linearized(source_dn),
257                                        ldb_dn_get_linearized(target_dn),
258                                        ldb_errstring(ldb));
259                 talloc_free(tmp_ctx);
260                 return ret;
261         }
262         talloc_free(tmp_ctx);
263         return ret;
264 }
265
266 /*
267   add a backlink to the list of backlinks to add/delete in the prepare
268   commit
269  */
270 static int replmd_add_backlink(struct ldb_module *module, const struct dsdb_schema *schema,
271                                struct GUID *forward_guid, struct GUID *target_guid,
272                                bool active, const struct dsdb_attribute *schema_attr, bool immediate)
273 {
274         const struct dsdb_attribute *target_attr;
275         struct la_backlink *bl;
276         struct replmd_private *replmd_private =
277                 talloc_get_type_abort(ldb_module_get_private(module), struct replmd_private);
278
279         target_attr = dsdb_attribute_by_linkID(schema, schema_attr->linkID ^ 1);
280         if (!target_attr) {
281                 /*
282                  * windows 2003 has a broken schema where the
283                  * definition of msDS-IsDomainFor is missing (which is
284                  * supposed to be the backlink of the
285                  * msDS-HasDomainNCs attribute
286                  */
287                 return LDB_SUCCESS;
288         }
289
290         /* see if its already in the list */
291         for (bl=replmd_private->la_backlinks; bl; bl=bl->next) {
292                 if (GUID_equal(forward_guid, &bl->forward_guid) &&
293                     GUID_equal(target_guid, &bl->target_guid) &&
294                     (target_attr->lDAPDisplayName == bl->attr_name ||
295                      strcmp(target_attr->lDAPDisplayName, bl->attr_name) == 0)) {
296                         break;
297                 }
298         }
299
300         if (bl) {
301                 /* we found an existing one */
302                 if (bl->active == active) {
303                         return LDB_SUCCESS;
304                 }
305                 DLIST_REMOVE(replmd_private->la_backlinks, bl);
306                 talloc_free(bl);
307                 return LDB_SUCCESS;
308         }
309
310         if (replmd_private->bl_ctx == NULL) {
311                 replmd_private->bl_ctx = talloc_new(replmd_private);
312                 if (replmd_private->bl_ctx == NULL) {
313                         ldb_module_oom(module);
314                         return LDB_ERR_OPERATIONS_ERROR;
315                 }
316         }
317
318         /* its a new one */
319         bl = talloc(replmd_private->bl_ctx, struct la_backlink);
320         if (bl == NULL) {
321                 ldb_module_oom(module);
322                 return LDB_ERR_OPERATIONS_ERROR;
323         }
324
325         /* Ensure the schema does not go away before the bl->attr_name is used */
326         if (!talloc_reference(bl, schema)) {
327                 talloc_free(bl);
328                 ldb_module_oom(module);
329                 return LDB_ERR_OPERATIONS_ERROR;
330         }
331
332         bl->attr_name = target_attr->lDAPDisplayName;
333         bl->forward_guid = *forward_guid;
334         bl->target_guid = *target_guid;
335         bl->active = active;
336
337         /* the caller may ask for this backlink to be processed
338            immediately */
339         if (immediate) {
340                 int ret = replmd_process_backlink(module, bl);
341                 talloc_free(bl);
342                 return ret;
343         }
344
345         DLIST_ADD(replmd_private->la_backlinks, bl);
346
347         return LDB_SUCCESS;
348 }
349
350
351 /*
352  * Callback for most write operations in this module:
353  * 
354  * notify the repl task that a object has changed. The notifies are
355  * gathered up in the replmd_private structure then written to the
356  * @REPLCHANGED object in each partition during the prepare_commit
357  */
358 static int replmd_op_callback(struct ldb_request *req, struct ldb_reply *ares)
359 {
360         int ret;
361         struct replmd_replicated_request *ac = 
362                 talloc_get_type_abort(req->context, struct replmd_replicated_request);
363         struct replmd_private *replmd_private = 
364                 talloc_get_type_abort(ldb_module_get_private(ac->module), struct replmd_private);
365         struct nc_entry *modified_partition;
366         struct ldb_control *partition_ctrl;
367         const struct dsdb_control_current_partition *partition;
368
369         struct ldb_control **controls;
370
371         partition_ctrl = ldb_reply_get_control(ares, DSDB_CONTROL_CURRENT_PARTITION_OID);
372
373         /* Remove the 'partition' control from what we pass up the chain */
374         controls = controls_except_specified(ares->controls, ares, partition_ctrl);
375
376         if (ares->error != LDB_SUCCESS) {
377                 return ldb_module_done(ac->req, controls,
378                                         ares->response, ares->error);
379         }
380
381         if (ares->type != LDB_REPLY_DONE) {
382                 ldb_set_errstring(ldb_module_get_ctx(ac->module), "Invalid reply type for notify\n!");
383                 return ldb_module_done(ac->req, NULL,
384                                        NULL, LDB_ERR_OPERATIONS_ERROR);
385         }
386
387         if (!partition_ctrl) {
388                 ldb_set_errstring(ldb_module_get_ctx(ac->module),"No partition control on reply");
389                 return ldb_module_done(ac->req, NULL,
390                                        NULL, LDB_ERR_OPERATIONS_ERROR);
391         }
392
393         partition = talloc_get_type_abort(partition_ctrl->data,
394                                     struct dsdb_control_current_partition);
395         
396         if (ac->seq_num > 0) {
397                 for (modified_partition = replmd_private->ncs; modified_partition; 
398                      modified_partition = modified_partition->next) {
399                         if (ldb_dn_compare(modified_partition->dn, partition->dn) == 0) {
400                                 break;
401                         }
402                 }
403                 
404                 if (modified_partition == NULL) {
405                         modified_partition = talloc_zero(replmd_private, struct nc_entry);
406                         if (!modified_partition) {
407                                 ldb_oom(ldb_module_get_ctx(ac->module));
408                                 return ldb_module_done(ac->req, NULL,
409                                                        NULL, LDB_ERR_OPERATIONS_ERROR);
410                         }
411                         modified_partition->dn = ldb_dn_copy(modified_partition, partition->dn);
412                         if (!modified_partition->dn) {
413                                 ldb_oom(ldb_module_get_ctx(ac->module));
414                                 return ldb_module_done(ac->req, NULL,
415                                                        NULL, LDB_ERR_OPERATIONS_ERROR);
416                         }
417                         DLIST_ADD(replmd_private->ncs, modified_partition);
418                 }
419
420                 if (ac->seq_num > modified_partition->mod_usn) {
421                         modified_partition->mod_usn = ac->seq_num;
422                         if (ac->is_urgent) {
423                                 modified_partition->mod_usn_urgent = ac->seq_num;
424                         }
425                 }
426         }
427
428         if (ac->apply_mode) {
429                 talloc_free(ares);
430                 ac->index_current++;
431                 
432                 ret = replmd_replicated_apply_next(ac);
433                 if (ret != LDB_SUCCESS) {
434                         return ldb_module_done(ac->req, NULL, NULL, ret);
435                 }
436                 return ret;
437         } else {
438                 /* free the partition control container here, for the
439                  * common path.  Other cases will have it cleaned up
440                  * eventually with the ares */
441                 talloc_free(partition_ctrl);
442                 return ldb_module_done(ac->req, 
443                                        controls_except_specified(controls, ares, partition_ctrl),
444                                        ares->response, LDB_SUCCESS);
445         }
446 }
447
448
449 /*
450  * update a @REPLCHANGED record in each partition if there have been
451  * any writes of replicated data in the partition
452  */
453 static int replmd_notify_store(struct ldb_module *module)
454 {
455         struct replmd_private *replmd_private =
456                 talloc_get_type(ldb_module_get_private(module), struct replmd_private);
457
458         while (replmd_private->ncs) {
459                 int ret;
460                 struct nc_entry *modified_partition = replmd_private->ncs;
461
462                 ret = dsdb_module_save_partition_usn(module, modified_partition->dn,
463                                                      modified_partition->mod_usn,
464                                                      modified_partition->mod_usn_urgent);
465                 if (ret != LDB_SUCCESS) {
466                         DEBUG(0,(__location__ ": Failed to save partition uSN for %s\n",
467                                  ldb_dn_get_linearized(modified_partition->dn)));
468                         return ret;
469                 }
470                 DLIST_REMOVE(replmd_private->ncs, modified_partition);
471                 talloc_free(modified_partition);
472         }
473
474         return LDB_SUCCESS;
475 }
476
477
478 /*
479   created a replmd_replicated_request context
480  */
481 static struct replmd_replicated_request *replmd_ctx_init(struct ldb_module *module,
482                                                          struct ldb_request *req)
483 {
484         struct ldb_context *ldb;
485         struct replmd_replicated_request *ac;
486
487         ldb = ldb_module_get_ctx(module);
488
489         ac = talloc_zero(req, struct replmd_replicated_request);
490         if (ac == NULL) {
491                 ldb_oom(ldb);
492                 return NULL;
493         }
494
495         ac->module = module;
496         ac->req = req;
497
498         ac->schema = dsdb_get_schema(ldb, ac);
499         if (!ac->schema) {
500                 ldb_debug_set(ldb, LDB_DEBUG_FATAL,
501                               "replmd_modify: no dsdb_schema loaded");
502                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
503                 return NULL;
504         }
505
506         return ac;
507 }
508
509 /*
510   add a time element to a record
511 */
512 static int add_time_element(struct ldb_message *msg, const char *attr, time_t t)
513 {
514         struct ldb_message_element *el;
515         char *s;
516
517         if (ldb_msg_find_element(msg, attr) != NULL) {
518                 return LDB_SUCCESS;
519         }
520
521         s = ldb_timestring(msg, t);
522         if (s == NULL) {
523                 return LDB_ERR_OPERATIONS_ERROR;
524         }
525
526         if (ldb_msg_add_string(msg, attr, s) != LDB_SUCCESS) {
527                 return LDB_ERR_OPERATIONS_ERROR;
528         }
529
530         el = ldb_msg_find_element(msg, attr);
531         /* always set as replace. This works because on add ops, the flag
532            is ignored */
533         el->flags = LDB_FLAG_MOD_REPLACE;
534
535         return LDB_SUCCESS;
536 }
537
538 /*
539   add a uint64_t element to a record
540 */
541 static int add_uint64_element(struct ldb_message *msg, const char *attr, uint64_t v)
542 {
543         struct ldb_message_element *el;
544
545         if (ldb_msg_find_element(msg, attr) != NULL) {
546                 return LDB_SUCCESS;
547         }
548
549         if (ldb_msg_add_fmt(msg, attr, "%llu", (unsigned long long)v) != LDB_SUCCESS) {
550                 return LDB_ERR_OPERATIONS_ERROR;
551         }
552
553         el = ldb_msg_find_element(msg, attr);
554         /* always set as replace. This works because on add ops, the flag
555            is ignored */
556         el->flags = LDB_FLAG_MOD_REPLACE;
557
558         return LDB_SUCCESS;
559 }
560
561 static int replmd_replPropertyMetaData1_attid_sort(const struct replPropertyMetaData1 *m1,
562                                                    const struct replPropertyMetaData1 *m2,
563                                                    const uint32_t *rdn_attid)
564 {
565         if (m1->attid == m2->attid) {
566                 return 0;
567         }
568
569         /*
570          * the rdn attribute should be at the end!
571          * so we need to return a value greater than zero
572          * which means m1 is greater than m2
573          */
574         if (m1->attid == *rdn_attid) {
575                 return 1;
576         }
577
578         /*
579          * the rdn attribute should be at the end!
580          * so we need to return a value less than zero
581          * which means m2 is greater than m1
582          */
583         if (m2->attid == *rdn_attid) {
584                 return -1;
585         }
586
587         return m1->attid > m2->attid ? 1 : -1;
588 }
589
590 static int replmd_replPropertyMetaDataCtr1_sort(struct replPropertyMetaDataCtr1 *ctr1,
591                                                 const struct dsdb_schema *schema,
592                                                 struct ldb_dn *dn)
593 {
594         const char *rdn_name;
595         const struct dsdb_attribute *rdn_sa;
596
597         rdn_name = ldb_dn_get_rdn_name(dn);
598         if (!rdn_name) {
599                 DEBUG(0,(__location__ ": No rDN for %s?\n", ldb_dn_get_linearized(dn)));
600                 return LDB_ERR_OPERATIONS_ERROR;
601         }
602
603         rdn_sa = dsdb_attribute_by_lDAPDisplayName(schema, rdn_name);
604         if (rdn_sa == NULL) {
605                 DEBUG(0,(__location__ ": No sa found for rDN %s for %s\n", rdn_name, ldb_dn_get_linearized(dn)));
606                 return LDB_ERR_OPERATIONS_ERROR;                
607         }
608
609         DEBUG(6,("Sorting rpmd with attid exception %u rDN=%s DN=%s\n", 
610                  rdn_sa->attributeID_id, rdn_name, ldb_dn_get_linearized(dn)));
611
612         LDB_TYPESAFE_QSORT(ctr1->array, ctr1->count, &rdn_sa->attributeID_id, replmd_replPropertyMetaData1_attid_sort);
613
614         return LDB_SUCCESS;
615 }
616
617 static int replmd_ldb_message_element_attid_sort(const struct ldb_message_element *e1,
618                                                  const struct ldb_message_element *e2,
619                                                  const struct dsdb_schema *schema)
620 {
621         const struct dsdb_attribute *a1;
622         const struct dsdb_attribute *a2;
623
624         /* 
625          * TODO: make this faster by caching the dsdb_attribute pointer
626          *       on the ldb_messag_element
627          */
628
629         a1 = dsdb_attribute_by_lDAPDisplayName(schema, e1->name);
630         a2 = dsdb_attribute_by_lDAPDisplayName(schema, e2->name);
631
632         /*
633          * TODO: remove this check, we should rely on e1 and e2 having valid attribute names
634          *       in the schema
635          */
636         if (!a1 || !a2) {
637                 return strcasecmp(e1->name, e2->name);
638         }
639         if (a1->attributeID_id == a2->attributeID_id) {
640                 return 0;
641         }
642         return a1->attributeID_id > a2->attributeID_id ? 1 : -1;
643 }
644
645 static void replmd_ldb_message_sort(struct ldb_message *msg,
646                                     const struct dsdb_schema *schema)
647 {
648         LDB_TYPESAFE_QSORT(msg->elements, msg->num_elements, schema, replmd_ldb_message_element_attid_sort);
649 }
650
651 static int replmd_build_la_val(TALLOC_CTX *mem_ctx, struct ldb_val *v, struct dsdb_dn *dsdb_dn,
652                                const struct GUID *invocation_id, uint64_t seq_num,
653                                uint64_t local_usn, NTTIME nttime, uint32_t version, bool deleted);
654
655
656 /*
657   fix up linked attributes in replmd_add.
658   This involves setting up the right meta-data in extended DN
659   components, and creating backlinks to the object
660  */
661 static int replmd_add_fix_la(struct ldb_module *module, struct ldb_message_element *el,
662                              uint64_t seq_num, const struct GUID *invocationId, time_t t,
663                              struct GUID *guid, const struct dsdb_attribute *sa)
664 {
665         unsigned int i;
666         TALLOC_CTX *tmp_ctx = talloc_new(el->values);
667         struct ldb_context *ldb = ldb_module_get_ctx(module);
668
669         /* We will take a reference to the schema in replmd_add_backlink */
670         const struct dsdb_schema *schema = dsdb_get_schema(ldb, NULL);
671         NTTIME now;
672
673         unix_to_nt_time(&now, t);
674
675         for (i=0; i<el->num_values; i++) {
676                 struct ldb_val *v = &el->values[i];
677                 struct dsdb_dn *dsdb_dn = dsdb_dn_parse(tmp_ctx, ldb, v, sa->syntax->ldap_oid);
678                 struct GUID target_guid;
679                 NTSTATUS status;
680                 int ret;
681
682                 /* note that the DN already has the extended
683                    components from the extended_dn_store module */
684                 status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &target_guid, "GUID");
685                 if (!NT_STATUS_IS_OK(status) || GUID_all_zero(&target_guid)) {
686                         ret = dsdb_module_guid_by_dn(module, dsdb_dn->dn, &target_guid);
687                         if (ret != LDB_SUCCESS) {
688                                 talloc_free(tmp_ctx);
689                                 return ret;
690                         }
691                         ret = dsdb_set_extended_dn_guid(dsdb_dn->dn, &target_guid, "GUID");
692                         if (ret != LDB_SUCCESS) {
693                                 talloc_free(tmp_ctx);
694                                 return ret;
695                         }
696                 }
697
698                 ret = replmd_build_la_val(el->values, v, dsdb_dn, invocationId,
699                                           seq_num, seq_num, now, 0, false);
700                 if (ret != LDB_SUCCESS) {
701                         talloc_free(tmp_ctx);
702                         return ret;
703                 }
704
705                 ret = replmd_add_backlink(module, schema, guid, &target_guid, true, sa, false);
706                 if (ret != LDB_SUCCESS) {
707                         talloc_free(tmp_ctx);
708                         return ret;
709                 }
710         }
711
712         talloc_free(tmp_ctx);
713         return LDB_SUCCESS;
714 }
715
716
717 /*
718   intercept add requests
719  */
720 static int replmd_add(struct ldb_module *module, struct ldb_request *req)
721 {
722         struct ldb_context *ldb;
723         struct ldb_control *control;
724         struct replmd_replicated_request *ac;
725         enum ndr_err_code ndr_err;
726         struct ldb_request *down_req;
727         struct ldb_message *msg;
728         const DATA_BLOB *guid_blob;
729         struct GUID guid;
730         struct replPropertyMetaDataBlob nmd;
731         struct ldb_val nmd_value;
732         const struct GUID *our_invocation_id;
733         time_t t = time(NULL);
734         NTTIME now;
735         char *time_str;
736         int ret;
737         unsigned int i;
738         uint32_t ni=0;
739         bool allow_add_guid = false;
740         bool remove_current_guid = false;
741         bool is_urgent = false;
742         struct ldb_message_element *objectclass_el;
743
744         /* check if there's a show relax control (used by provision to say 'I know what I'm doing') */
745         control = ldb_request_get_control(req, LDB_CONTROL_RELAX_OID);
746         if (control) {
747                 allow_add_guid = true;
748         }
749
750         /* do not manipulate our control entries */
751         if (ldb_dn_is_special(req->op.add.message->dn)) {
752                 return ldb_next_request(module, req);
753         }
754
755         ldb = ldb_module_get_ctx(module);
756
757         ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_add\n");
758
759         ac = replmd_ctx_init(module, req);
760         if (!ac) {
761                 return LDB_ERR_OPERATIONS_ERROR;
762         }
763
764         guid_blob = ldb_msg_find_ldb_val(req->op.add.message, "objectGUID");
765         if ( guid_blob != NULL ) {
766                 if( !allow_add_guid ) {
767                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
768                               "replmd_add: it's not allowed to add an object with objectGUID\n");
769                         talloc_free(ac);
770                         return LDB_ERR_UNWILLING_TO_PERFORM;
771                 } else {
772                         NTSTATUS status = GUID_from_data_blob(guid_blob,&guid);
773                         if ( !NT_STATUS_IS_OK(status)) {
774                                 ldb_debug_set(ldb, LDB_DEBUG_ERROR,
775                                       "replmd_add: Unable to parse as a GUID the attribute objectGUID\n");
776                                 talloc_free(ac);
777                                 return LDB_ERR_UNWILLING_TO_PERFORM;
778                         }
779                         /* we remove this attribute as it can be a string and will not be treated 
780                         correctly and then we will readd it latter on in the good format*/
781                         remove_current_guid = true;
782                 }
783         } else {
784                 /* a new GUID */
785                 guid = GUID_random();
786         }
787
788         /* Get a sequence number from the backend */
789         ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &ac->seq_num);
790         if (ret != LDB_SUCCESS) {
791                 talloc_free(ac);
792                 return ret;
793         }
794
795         /* get our invocationId */
796         our_invocation_id = samdb_ntds_invocation_id(ldb);
797         if (!our_invocation_id) {
798                 ldb_debug_set(ldb, LDB_DEBUG_ERROR,
799                               "replmd_add: unable to find invocationId\n");
800                 talloc_free(ac);
801                 return LDB_ERR_OPERATIONS_ERROR;
802         }
803
804         /* we have to copy the message as the caller might have it as a const */
805         msg = ldb_msg_copy_shallow(ac, req->op.add.message);
806         if (msg == NULL) {
807                 ldb_oom(ldb);
808                 talloc_free(ac);
809                 return LDB_ERR_OPERATIONS_ERROR;
810         }
811
812         /* generated times */
813         unix_to_nt_time(&now, t);
814         time_str = ldb_timestring(msg, t);
815         if (!time_str) {
816                 ldb_oom(ldb);
817                 talloc_free(ac);
818                 return LDB_ERR_OPERATIONS_ERROR;
819         }
820         if (remove_current_guid) {
821                 ldb_msg_remove_attr(msg,"objectGUID");
822         }
823
824         /* 
825          * remove autogenerated attributes
826          */
827         ldb_msg_remove_attr(msg, "whenCreated");
828         ldb_msg_remove_attr(msg, "whenChanged");
829         ldb_msg_remove_attr(msg, "uSNCreated");
830         ldb_msg_remove_attr(msg, "uSNChanged");
831         ldb_msg_remove_attr(msg, "replPropertyMetaData");
832
833         /*
834          * readd replicated attributes
835          */
836         ret = ldb_msg_add_string(msg, "whenCreated", time_str);
837         if (ret != LDB_SUCCESS) {
838                 ldb_oom(ldb);
839                 talloc_free(ac);
840                 return ret;
841         }
842
843         /* build the replication meta_data */
844         ZERO_STRUCT(nmd);
845         nmd.version             = 1;
846         nmd.ctr.ctr1.count      = msg->num_elements;
847         nmd.ctr.ctr1.array      = talloc_array(msg,
848                                                struct replPropertyMetaData1,
849                                                nmd.ctr.ctr1.count);
850         if (!nmd.ctr.ctr1.array) {
851                 ldb_oom(ldb);
852                 talloc_free(ac);
853                 return LDB_ERR_OPERATIONS_ERROR;
854         }
855
856         for (i=0; i < msg->num_elements; i++) {
857                 struct ldb_message_element *e = &msg->elements[i];
858                 struct replPropertyMetaData1 *m = &nmd.ctr.ctr1.array[ni];
859                 const struct dsdb_attribute *sa;
860
861                 if (e->name[0] == '@') continue;
862
863                 sa = dsdb_attribute_by_lDAPDisplayName(ac->schema, e->name);
864                 if (!sa) {
865                         ldb_debug_set(ldb, LDB_DEBUG_ERROR,
866                                       "replmd_add: attribute '%s' not defined in schema\n",
867                                       e->name);
868                         talloc_free(ac);
869                         return LDB_ERR_NO_SUCH_ATTRIBUTE;
870                 }
871
872                 if ((sa->systemFlags & DS_FLAG_ATTR_NOT_REPLICATED) || (sa->systemFlags & DS_FLAG_ATTR_IS_CONSTRUCTED)) {
873                         /* if the attribute is not replicated (0x00000001)
874                          * or constructed (0x00000004) it has no metadata
875                          */
876                         continue;
877                 }
878
879 #if W2K3_LINKED_ATTRIBUTES
880                 if (sa->linkID != 0 && dsdb_functional_level(ldb) > DS_DOMAIN_FUNCTION_2000) {
881                         ret = replmd_add_fix_la(module, e, ac->seq_num, our_invocation_id, t, &guid, sa);
882                         if (ret != LDB_SUCCESS) {
883                                 talloc_free(ac);
884                                 return ret;
885                         }
886                         /* linked attributes are not stored in
887                            replPropertyMetaData in FL above w2k */
888                         continue;
889                 }
890 #endif
891
892                 m->attid                        = sa->attributeID_id;
893                 m->version                      = 1;
894                 m->originating_change_time      = now;
895                 m->originating_invocation_id    = *our_invocation_id;
896                 m->originating_usn              = ac->seq_num;
897                 m->local_usn                    = ac->seq_num;
898                 ni++;
899         }
900
901         /* fix meta data count */
902         nmd.ctr.ctr1.count = ni;
903
904         /*
905          * sort meta data array, and move the rdn attribute entry to the end
906          */
907         ret = replmd_replPropertyMetaDataCtr1_sort(&nmd.ctr.ctr1, ac->schema, msg->dn);
908         if (ret != LDB_SUCCESS) {
909                 talloc_free(ac);
910                 return ret;
911         }
912
913         /* generated NDR encoded values */
914         ndr_err = ndr_push_struct_blob(&nmd_value, msg, 
915                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
916                                        &nmd,
917                                        (ndr_push_flags_fn_t)ndr_push_replPropertyMetaDataBlob);
918         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
919                 ldb_oom(ldb);
920                 talloc_free(ac);
921                 return LDB_ERR_OPERATIONS_ERROR;
922         }
923
924         /*
925          * add the autogenerated values
926          */
927         ret = dsdb_msg_add_guid(msg, &guid, "objectGUID");
928         if (ret != LDB_SUCCESS) {
929                 ldb_oom(ldb);
930                 talloc_free(ac);
931                 return ret;
932         }
933         ret = ldb_msg_add_string(msg, "whenChanged", time_str);
934         if (ret != LDB_SUCCESS) {
935                 ldb_oom(ldb);
936                 talloc_free(ac);
937                 return ret;
938         }
939         ret = samdb_msg_add_uint64(ldb, msg, msg, "uSNCreated", ac->seq_num);
940         if (ret != LDB_SUCCESS) {
941                 ldb_oom(ldb);
942                 talloc_free(ac);
943                 return ret;
944         }
945         ret = samdb_msg_add_uint64(ldb, msg, msg, "uSNChanged", ac->seq_num);
946         if (ret != LDB_SUCCESS) {
947                 ldb_oom(ldb);
948                 talloc_free(ac);
949                 return ret;
950         }
951         ret = ldb_msg_add_value(msg, "replPropertyMetaData", &nmd_value, NULL);
952         if (ret != LDB_SUCCESS) {
953                 ldb_oom(ldb);
954                 talloc_free(ac);
955                 return ret;
956         }
957
958         /*
959          * sort the attributes by attid before storing the object
960          */
961         replmd_ldb_message_sort(msg, ac->schema);
962
963         objectclass_el = ldb_msg_find_element(msg, "objectClass");
964         is_urgent = replmd_check_urgent_objectclass(objectclass_el,
965                                                         REPL_URGENT_ON_CREATE);
966
967         ac->is_urgent = is_urgent;
968         ret = ldb_build_add_req(&down_req, ldb, ac,
969                                 msg,
970                                 req->controls,
971                                 ac, replmd_op_callback,
972                                 req);
973
974         if (ret != LDB_SUCCESS) {
975                 talloc_free(ac);
976                 return ret;
977         }
978
979         /* mark the control done */
980         if (control) {
981                 control->critical = 0;
982         }
983
984         /* go on with the call chain */
985         return ldb_next_request(module, down_req);
986 }
987
988
989 /*
990  * update the replPropertyMetaData for one element
991  */
992 static int replmd_update_rpmd_element(struct ldb_context *ldb,
993                                       struct ldb_message *msg,
994                                       struct ldb_message_element *el,
995                                       struct ldb_message_element *old_el,
996                                       struct replPropertyMetaDataBlob *omd,
997                                       const struct dsdb_schema *schema,
998                                       uint64_t *seq_num,
999                                       const struct GUID *our_invocation_id,
1000                                       NTTIME now)
1001 {
1002         uint32_t i;
1003         const struct dsdb_attribute *a;
1004         struct replPropertyMetaData1 *md1;
1005
1006         a = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
1007         if (a == NULL) {
1008                 DEBUG(0,(__location__ ": Unable to find attribute %s in schema\n",
1009                          el->name));
1010                 return LDB_ERR_OPERATIONS_ERROR;
1011         }
1012
1013         if ((a->systemFlags & DS_FLAG_ATTR_NOT_REPLICATED) || (a->systemFlags & DS_FLAG_ATTR_IS_CONSTRUCTED)) {
1014                 return LDB_SUCCESS;
1015         }
1016
1017         /* if the attribute's value haven't changed then return LDB_SUCCESS     */
1018         if (old_el != NULL && ldb_msg_element_compare(el, old_el) == 0) {
1019                 return LDB_SUCCESS;
1020         }
1021
1022         for (i=0; i<omd->ctr.ctr1.count; i++) {
1023                 if (a->attributeID_id == omd->ctr.ctr1.array[i].attid) break;
1024         }
1025
1026 #if W2K3_LINKED_ATTRIBUTES
1027         if (a->linkID != 0 && dsdb_functional_level(ldb) > DS_DOMAIN_FUNCTION_2000) {
1028                 /* linked attributes are not stored in
1029                    replPropertyMetaData in FL above w2k, but we do
1030                    raise the seqnum for the object  */
1031                 if (*seq_num == 0 &&
1032                     ldb_sequence_number(ldb, LDB_SEQ_NEXT, seq_num) != LDB_SUCCESS) {
1033                         return LDB_ERR_OPERATIONS_ERROR;
1034                 }
1035                 return LDB_SUCCESS;
1036         }
1037 #endif
1038
1039         if (i == omd->ctr.ctr1.count) {
1040                 /* we need to add a new one */
1041                 omd->ctr.ctr1.array = talloc_realloc(msg, omd->ctr.ctr1.array, 
1042                                                      struct replPropertyMetaData1, omd->ctr.ctr1.count+1);
1043                 if (omd->ctr.ctr1.array == NULL) {
1044                         ldb_oom(ldb);
1045                         return LDB_ERR_OPERATIONS_ERROR;
1046                 }
1047                 omd->ctr.ctr1.count++;
1048                 ZERO_STRUCT(omd->ctr.ctr1.array[i]);
1049         }
1050
1051         /* Get a new sequence number from the backend. We only do this
1052          * if we have a change that requires a new
1053          * replPropertyMetaData element 
1054          */
1055         if (*seq_num == 0) {
1056                 int ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, seq_num);
1057                 if (ret != LDB_SUCCESS) {
1058                         return LDB_ERR_OPERATIONS_ERROR;
1059                 }
1060         }
1061
1062         md1 = &omd->ctr.ctr1.array[i];
1063         md1->version++;
1064         md1->attid                     = a->attributeID_id;
1065         md1->originating_change_time   = now;
1066         md1->originating_invocation_id = *our_invocation_id;
1067         md1->originating_usn           = *seq_num;
1068         md1->local_usn                 = *seq_num;
1069         
1070         return LDB_SUCCESS;
1071 }
1072
1073 /*
1074  * update the replPropertyMetaData object each time we modify an
1075  * object. This is needed for DRS replication, as the merge on the
1076  * client is based on this object 
1077  */
1078 static int replmd_update_rpmd(struct ldb_module *module, 
1079                               const struct dsdb_schema *schema, 
1080                               struct ldb_message *msg, uint64_t *seq_num,
1081                               time_t t,
1082                               bool *is_urgent)
1083 {
1084         const struct ldb_val *omd_value;
1085         enum ndr_err_code ndr_err;
1086         struct replPropertyMetaDataBlob omd;
1087         unsigned int i;
1088         NTTIME now;
1089         const struct GUID *our_invocation_id;
1090         int ret;
1091         const char *attrs[] = { "replPropertyMetaData", "*", NULL };
1092         struct ldb_result *res;
1093         struct ldb_context *ldb;
1094         struct ldb_message_element *objectclass_el;
1095         enum urgent_situation situation;
1096
1097         ldb = ldb_module_get_ctx(module);
1098
1099         our_invocation_id = samdb_ntds_invocation_id(ldb);
1100         if (!our_invocation_id) {
1101                 /* this happens during an initial vampire while
1102                    updating the schema */
1103                 DEBUG(5,("No invocationID - skipping replPropertyMetaData update\n"));
1104                 return LDB_SUCCESS;
1105         }
1106
1107         unix_to_nt_time(&now, t);
1108
1109         /* search for the existing replPropertyMetaDataBlob. We need
1110          * to use REVEAL and ask for DNs in storage format to support
1111          * the check for values being the same in
1112          * replmd_update_rpmd_element()
1113          */
1114         ret = dsdb_module_search_dn(module, msg, &res, msg->dn, attrs,
1115                                     DSDB_SEARCH_SHOW_DELETED |
1116                                     DSDB_SEARCH_SHOW_EXTENDED_DN |
1117                                     DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT |
1118                                     DSDB_SEARCH_REVEAL_INTERNALS);
1119         if (ret != LDB_SUCCESS || res->count != 1) {
1120                 DEBUG(0,(__location__ ": Object %s failed to find replPropertyMetaData\n",
1121                          ldb_dn_get_linearized(msg->dn)));
1122                 return LDB_ERR_OPERATIONS_ERROR;
1123         }
1124
1125         /* if isDeleted is present and is TRUE, then we consider we are deleting,
1126          * otherwise we consider we are updating */
1127         if (ldb_msg_check_string_attribute(msg, "isDeleted", "TRUE")) {
1128                 situation = REPL_URGENT_ON_DELETE;
1129         } else {
1130                 situation = REPL_URGENT_ON_UPDATE;
1131         }
1132
1133         objectclass_el = ldb_msg_find_element(res->msgs[0], "objectClass");
1134         if (is_urgent && replmd_check_urgent_objectclass(objectclass_el,
1135                                                         situation)) {
1136                 *is_urgent = true;
1137         }
1138
1139         omd_value = ldb_msg_find_ldb_val(res->msgs[0], "replPropertyMetaData");
1140         if (!omd_value) {
1141                 DEBUG(0,(__location__ ": Object %s does not have a replPropertyMetaData attribute\n",
1142                          ldb_dn_get_linearized(msg->dn)));
1143                 return LDB_ERR_OPERATIONS_ERROR;
1144         }
1145
1146         ndr_err = ndr_pull_struct_blob(omd_value, msg,
1147                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), &omd,
1148                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
1149         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1150                 DEBUG(0,(__location__ ": Failed to parse replPropertyMetaData for %s\n",
1151                          ldb_dn_get_linearized(msg->dn)));
1152                 return LDB_ERR_OPERATIONS_ERROR;
1153         }
1154
1155         if (omd.version != 1) {
1156                 DEBUG(0,(__location__ ": bad version %u in replPropertyMetaData for %s\n",
1157                          omd.version, ldb_dn_get_linearized(msg->dn)));
1158                 return LDB_ERR_OPERATIONS_ERROR;
1159         }
1160
1161         for (i=0; i<msg->num_elements; i++) {
1162                 struct ldb_message_element *old_el;
1163                 old_el = ldb_msg_find_element(res->msgs[0], msg->elements[i].name);
1164                 ret = replmd_update_rpmd_element(ldb, msg, &msg->elements[i], old_el, &omd, schema, seq_num,
1165                                                  our_invocation_id, now);
1166                 if (ret != LDB_SUCCESS) {
1167                         return ret;
1168                 }
1169
1170                 if (is_urgent && !*is_urgent && (situation == REPL_URGENT_ON_UPDATE)) {
1171                         *is_urgent = replmd_check_urgent_attribute(&msg->elements[i]);
1172                 }
1173
1174         }
1175
1176         /*
1177          * replmd_update_rpmd_element has done an update if the
1178          * seq_num is set
1179          */
1180         if (*seq_num != 0) {
1181                 struct ldb_val *md_value;
1182                 struct ldb_message_element *el;
1183
1184                 md_value = talloc(msg, struct ldb_val);
1185                 if (md_value == NULL) {
1186                         ldb_oom(ldb);
1187                         return LDB_ERR_OPERATIONS_ERROR;
1188                 }
1189
1190                 ret = replmd_replPropertyMetaDataCtr1_sort(&omd.ctr.ctr1, schema, msg->dn);
1191                 if (ret != LDB_SUCCESS) {
1192                         return ret;
1193                 }
1194
1195                 ndr_err = ndr_push_struct_blob(md_value, msg, 
1196                                                lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
1197                                                &omd,
1198                                                (ndr_push_flags_fn_t)ndr_push_replPropertyMetaDataBlob);
1199                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1200                         DEBUG(0,(__location__ ": Failed to marshall replPropertyMetaData for %s\n",
1201                                  ldb_dn_get_linearized(msg->dn)));
1202                         return LDB_ERR_OPERATIONS_ERROR;
1203                 }
1204
1205                 ret = ldb_msg_add_empty(msg, "replPropertyMetaData", LDB_FLAG_MOD_REPLACE, &el);
1206                 if (ret != LDB_SUCCESS) {
1207                         DEBUG(0,(__location__ ": Failed to add updated replPropertyMetaData %s\n",
1208                                  ldb_dn_get_linearized(msg->dn)));
1209                         return ret;
1210                 }
1211
1212                 el->num_values = 1;
1213                 el->values = md_value;
1214         }
1215
1216         return LDB_SUCCESS;     
1217 }
1218
1219 struct parsed_dn {
1220         struct dsdb_dn *dsdb_dn;
1221         struct GUID *guid;
1222         struct ldb_val *v;
1223 };
1224
1225 static int parsed_dn_compare(struct parsed_dn *pdn1, struct parsed_dn *pdn2)
1226 {
1227         return GUID_compare(pdn1->guid, pdn2->guid);
1228 }
1229
1230 static struct parsed_dn *parsed_dn_find(struct parsed_dn *pdn, int count, struct GUID *guid, struct ldb_dn *dn)
1231 {
1232         struct parsed_dn *ret;
1233         if (dn && GUID_all_zero(guid)) {
1234                 /* when updating a link using DRS, we sometimes get a
1235                    NULL GUID. We then need to try and match by DN */
1236                 int i;
1237                 for (i=0; i<count; i++) {
1238                         if (ldb_dn_compare(pdn[i].dsdb_dn->dn, dn) == 0) {
1239                                 dsdb_get_extended_dn_guid(pdn[i].dsdb_dn->dn, guid, "GUID");
1240                                 return &pdn[i];
1241                         }
1242                 }
1243                 return NULL;
1244         }
1245         BINARY_ARRAY_SEARCH(pdn, count, guid, guid, GUID_compare, ret);
1246         return ret;
1247 }
1248
1249 /*
1250   get a series of message element values as an array of DNs and GUIDs
1251   the result is sorted by GUID
1252  */
1253 static int get_parsed_dns(struct ldb_module *module, TALLOC_CTX *mem_ctx,
1254                           struct ldb_message_element *el, struct parsed_dn **pdn,
1255                           const char *ldap_oid)
1256 {
1257         unsigned int i;
1258         struct ldb_context *ldb = ldb_module_get_ctx(module);
1259
1260         if (el == NULL) {
1261                 *pdn = NULL;
1262                 return LDB_SUCCESS;
1263         }
1264
1265         (*pdn) = talloc_array(mem_ctx, struct parsed_dn, el->num_values);
1266         if (!*pdn) {
1267                 ldb_module_oom(module);
1268                 return LDB_ERR_OPERATIONS_ERROR;
1269         }
1270
1271         for (i=0; i<el->num_values; i++) {
1272                 struct ldb_val *v = &el->values[i];
1273                 NTSTATUS status;
1274                 struct ldb_dn *dn;
1275                 struct parsed_dn *p;
1276
1277                 p = &(*pdn)[i];
1278
1279                 p->dsdb_dn = dsdb_dn_parse(*pdn, ldb, v, ldap_oid);
1280                 if (p->dsdb_dn == NULL) {
1281                         return LDB_ERR_INVALID_DN_SYNTAX;
1282                 }
1283
1284                 dn = p->dsdb_dn->dn;
1285
1286                 p->guid = talloc(*pdn, struct GUID);
1287                 if (p->guid == NULL) {
1288                         ldb_module_oom(module);
1289                         return LDB_ERR_OPERATIONS_ERROR;
1290                 }
1291
1292                 status = dsdb_get_extended_dn_guid(dn, p->guid, "GUID");
1293                 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1294                         /* we got a DN without a GUID - go find the GUID */
1295                         int ret = dsdb_module_guid_by_dn(module, dn, p->guid);
1296                         if (ret != LDB_SUCCESS) {
1297                                 ldb_asprintf_errstring(ldb, "Unable to find GUID for DN %s\n",
1298                                                        ldb_dn_get_linearized(dn));
1299                                 return ret;
1300                         }
1301                         ret = dsdb_set_extended_dn_guid(dn, p->guid, "GUID");
1302                         if (ret != LDB_SUCCESS) {
1303                                 return ret;
1304                         }
1305                 } else if (!NT_STATUS_IS_OK(status)) {
1306                         return LDB_ERR_OPERATIONS_ERROR;
1307                 }
1308
1309                 /* keep a pointer to the original ldb_val */
1310                 p->v = v;
1311         }
1312
1313         TYPESAFE_QSORT(*pdn, el->num_values, parsed_dn_compare);
1314
1315         return LDB_SUCCESS;
1316 }
1317
1318 /*
1319   build a new extended DN, including all meta data fields
1320
1321   RMD_FLAGS           = DSDB_RMD_FLAG_* bits
1322   RMD_ADDTIME         = originating_add_time
1323   RMD_INVOCID         = originating_invocation_id
1324   RMD_CHANGETIME      = originating_change_time
1325   RMD_ORIGINATING_USN = originating_usn
1326   RMD_LOCAL_USN       = local_usn
1327   RMD_VERSION         = version
1328  */
1329 static int replmd_build_la_val(TALLOC_CTX *mem_ctx, struct ldb_val *v, struct dsdb_dn *dsdb_dn,
1330                                const struct GUID *invocation_id, uint64_t seq_num,
1331                                uint64_t local_usn, NTTIME nttime, uint32_t version, bool deleted)
1332 {
1333         struct ldb_dn *dn = dsdb_dn->dn;
1334         const char *tstring, *usn_string, *flags_string;
1335         struct ldb_val tval;
1336         struct ldb_val iid;
1337         struct ldb_val usnv, local_usnv;
1338         struct ldb_val vers, flagsv;
1339         NTSTATUS status;
1340         int ret;
1341         const char *dnstring;
1342         char *vstring;
1343         uint32_t rmd_flags = deleted?DSDB_RMD_FLAG_DELETED:0;
1344
1345         tstring = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)nttime);
1346         if (!tstring) {
1347                 return LDB_ERR_OPERATIONS_ERROR;
1348         }
1349         tval = data_blob_string_const(tstring);
1350
1351         usn_string = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)seq_num);
1352         if (!usn_string) {
1353                 return LDB_ERR_OPERATIONS_ERROR;
1354         }
1355         usnv = data_blob_string_const(usn_string);
1356
1357         usn_string = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)local_usn);
1358         if (!usn_string) {
1359                 return LDB_ERR_OPERATIONS_ERROR;
1360         }
1361         local_usnv = data_blob_string_const(usn_string);
1362
1363         vstring = talloc_asprintf(mem_ctx, "%lu", (unsigned long)version);
1364         if (!vstring) {
1365                 return LDB_ERR_OPERATIONS_ERROR;
1366         }
1367         vers = data_blob_string_const(vstring);
1368
1369         status = GUID_to_ndr_blob(invocation_id, dn, &iid);
1370         if (!NT_STATUS_IS_OK(status)) {
1371                 return LDB_ERR_OPERATIONS_ERROR;
1372         }
1373
1374         flags_string = talloc_asprintf(mem_ctx, "%u", rmd_flags);
1375         if (!flags_string) {
1376                 return LDB_ERR_OPERATIONS_ERROR;
1377         }
1378         flagsv = data_blob_string_const(flags_string);
1379
1380         ret = ldb_dn_set_extended_component(dn, "RMD_FLAGS", &flagsv);
1381         if (ret != LDB_SUCCESS) return ret;
1382         ret = ldb_dn_set_extended_component(dn, "RMD_ADDTIME", &tval);
1383         if (ret != LDB_SUCCESS) return ret;
1384         ret = ldb_dn_set_extended_component(dn, "RMD_INVOCID", &iid);
1385         if (ret != LDB_SUCCESS) return ret;
1386         ret = ldb_dn_set_extended_component(dn, "RMD_CHANGETIME", &tval);
1387         if (ret != LDB_SUCCESS) return ret;
1388         ret = ldb_dn_set_extended_component(dn, "RMD_LOCAL_USN", &local_usnv);
1389         if (ret != LDB_SUCCESS) return ret;
1390         ret = ldb_dn_set_extended_component(dn, "RMD_ORIGINATING_USN", &usnv);
1391         if (ret != LDB_SUCCESS) return ret;
1392         ret = ldb_dn_set_extended_component(dn, "RMD_VERSION", &vers);
1393         if (ret != LDB_SUCCESS) return ret;
1394
1395         dnstring = dsdb_dn_get_extended_linearized(mem_ctx, dsdb_dn, 1);
1396         if (dnstring == NULL) {
1397                 return LDB_ERR_OPERATIONS_ERROR;
1398         }
1399         *v = data_blob_string_const(dnstring);
1400
1401         return LDB_SUCCESS;
1402 }
1403
1404 static int replmd_update_la_val(TALLOC_CTX *mem_ctx, struct ldb_val *v, struct dsdb_dn *dsdb_dn,
1405                                 struct dsdb_dn *old_dsdb_dn, const struct GUID *invocation_id,
1406                                 uint64_t seq_num, uint64_t local_usn, NTTIME nttime,
1407                                 uint32_t version, bool deleted);
1408
1409 /*
1410   check if any links need upgrading from w2k format
1411  */
1412 static int replmd_check_upgrade_links(struct parsed_dn *dns, uint32_t count, const struct GUID *invocation_id)
1413 {
1414         uint32_t i;
1415         for (i=0; i<count; i++) {
1416                 NTSTATUS status;
1417                 uint32_t version;
1418                 int ret;
1419
1420                 status = dsdb_get_extended_dn_uint32(dns[i].dsdb_dn->dn, &version, "RMD_VERSION");
1421                 if (!NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1422                         continue;
1423                 }
1424
1425                 /* it's an old one that needs upgrading */
1426                 ret = replmd_update_la_val(dns, dns[i].v, dns[i].dsdb_dn, dns[i].dsdb_dn, invocation_id,
1427                                            1, 1, 0, 0, false);
1428                 if (ret != LDB_SUCCESS) {
1429                         return ret;
1430                 }
1431         }
1432         return LDB_SUCCESS;
1433 }
1434
1435 /*
1436   update an extended DN, including all meta data fields
1437
1438   see replmd_build_la_val for value names
1439  */
1440 static int replmd_update_la_val(TALLOC_CTX *mem_ctx, struct ldb_val *v, struct dsdb_dn *dsdb_dn,
1441                                 struct dsdb_dn *old_dsdb_dn, const struct GUID *invocation_id,
1442                                 uint64_t seq_num, uint64_t local_usn, NTTIME nttime,
1443                                 uint32_t version, bool deleted)
1444 {
1445         struct ldb_dn *dn = dsdb_dn->dn;
1446         const char *tstring, *usn_string, *flags_string;
1447         struct ldb_val tval;
1448         struct ldb_val iid;
1449         struct ldb_val usnv, local_usnv;
1450         struct ldb_val vers, flagsv;
1451         const struct ldb_val *old_addtime;
1452         uint32_t old_version;
1453         NTSTATUS status;
1454         int ret;
1455         const char *dnstring;
1456         char *vstring;
1457         uint32_t rmd_flags = deleted?DSDB_RMD_FLAG_DELETED:0;
1458
1459         tstring = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)nttime);
1460         if (!tstring) {
1461                 return LDB_ERR_OPERATIONS_ERROR;
1462         }
1463         tval = data_blob_string_const(tstring);
1464
1465         usn_string = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)seq_num);
1466         if (!usn_string) {
1467                 return LDB_ERR_OPERATIONS_ERROR;
1468         }
1469         usnv = data_blob_string_const(usn_string);
1470
1471         usn_string = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)local_usn);
1472         if (!usn_string) {
1473                 return LDB_ERR_OPERATIONS_ERROR;
1474         }
1475         local_usnv = data_blob_string_const(usn_string);
1476
1477         status = GUID_to_ndr_blob(invocation_id, dn, &iid);
1478         if (!NT_STATUS_IS_OK(status)) {
1479                 return LDB_ERR_OPERATIONS_ERROR;
1480         }
1481
1482         flags_string = talloc_asprintf(mem_ctx, "%u", rmd_flags);
1483         if (!flags_string) {
1484                 return LDB_ERR_OPERATIONS_ERROR;
1485         }
1486         flagsv = data_blob_string_const(flags_string);
1487
1488         ret = ldb_dn_set_extended_component(dn, "RMD_FLAGS", &flagsv);
1489         if (ret != LDB_SUCCESS) return ret;
1490
1491         /* get the ADDTIME from the original */
1492         old_addtime = ldb_dn_get_extended_component(old_dsdb_dn->dn, "RMD_ADDTIME");
1493         if (old_addtime == NULL) {
1494                 old_addtime = &tval;
1495         }
1496         if (dsdb_dn != old_dsdb_dn) {
1497                 ret = ldb_dn_set_extended_component(dn, "RMD_ADDTIME", old_addtime);
1498                 if (ret != LDB_SUCCESS) return ret;
1499         }
1500
1501         /* use our invocation id */
1502         ret = ldb_dn_set_extended_component(dn, "RMD_INVOCID", &iid);
1503         if (ret != LDB_SUCCESS) return ret;
1504
1505         /* changetime is the current time */
1506         ret = ldb_dn_set_extended_component(dn, "RMD_CHANGETIME", &tval);
1507         if (ret != LDB_SUCCESS) return ret;
1508
1509         /* update the USN */
1510         ret = ldb_dn_set_extended_component(dn, "RMD_ORIGINATING_USN", &usnv);
1511         if (ret != LDB_SUCCESS) return ret;
1512
1513         ret = ldb_dn_set_extended_component(dn, "RMD_LOCAL_USN", &local_usnv);
1514         if (ret != LDB_SUCCESS) return ret;
1515
1516         /* increase the version by 1 */
1517         status = dsdb_get_extended_dn_uint32(old_dsdb_dn->dn, &old_version, "RMD_VERSION");
1518         if (NT_STATUS_IS_OK(status) && old_version >= version) {
1519                 version = old_version+1;
1520         }
1521         vstring = talloc_asprintf(dn, "%lu", (unsigned long)version);
1522         vers = data_blob_string_const(vstring);
1523         ret = ldb_dn_set_extended_component(dn, "RMD_VERSION", &vers);
1524         if (ret != LDB_SUCCESS) return ret;
1525
1526         dnstring = dsdb_dn_get_extended_linearized(mem_ctx, dsdb_dn, 1);
1527         if (dnstring == NULL) {
1528                 return LDB_ERR_OPERATIONS_ERROR;
1529         }
1530         *v = data_blob_string_const(dnstring);
1531
1532         return LDB_SUCCESS;
1533 }
1534
1535 /*
1536   handle adding a linked attribute
1537  */
1538 static int replmd_modify_la_add(struct ldb_module *module,
1539                                 const struct dsdb_schema *schema,
1540                                 struct ldb_message *msg,
1541                                 struct ldb_message_element *el,
1542                                 struct ldb_message_element *old_el,
1543                                 const struct dsdb_attribute *schema_attr,
1544                                 uint64_t seq_num,
1545                                 time_t t,
1546                                 struct GUID *msg_guid)
1547 {
1548         unsigned int i;
1549         struct parsed_dn *dns, *old_dns;
1550         TALLOC_CTX *tmp_ctx = talloc_new(msg);
1551         int ret;
1552         struct ldb_val *new_values = NULL;
1553         unsigned int num_new_values = 0;
1554         unsigned old_num_values = old_el?old_el->num_values:0;
1555         const struct GUID *invocation_id;
1556         struct ldb_context *ldb = ldb_module_get_ctx(module);
1557         NTTIME now;
1558
1559         unix_to_nt_time(&now, t);
1560
1561         ret = get_parsed_dns(module, tmp_ctx, el, &dns, schema_attr->syntax->ldap_oid);
1562         if (ret != LDB_SUCCESS) {
1563                 talloc_free(tmp_ctx);
1564                 return ret;
1565         }
1566
1567         ret = get_parsed_dns(module, tmp_ctx, old_el, &old_dns, schema_attr->syntax->ldap_oid);
1568         if (ret != LDB_SUCCESS) {
1569                 talloc_free(tmp_ctx);
1570                 return ret;
1571         }
1572
1573         invocation_id = samdb_ntds_invocation_id(ldb);
1574         if (!invocation_id) {
1575                 talloc_free(tmp_ctx);
1576                 return LDB_ERR_OPERATIONS_ERROR;
1577         }
1578
1579         ret = replmd_check_upgrade_links(old_dns, old_num_values, invocation_id);
1580         if (ret != LDB_SUCCESS) {
1581                 talloc_free(tmp_ctx);
1582                 return ret;
1583         }
1584
1585         /* for each new value, see if it exists already with the same GUID */
1586         for (i=0; i<el->num_values; i++) {
1587                 struct parsed_dn *p = parsed_dn_find(old_dns, old_num_values, dns[i].guid, NULL);
1588                 if (p == NULL) {
1589                         /* this is a new linked attribute value */
1590                         new_values = talloc_realloc(tmp_ctx, new_values, struct ldb_val, num_new_values+1);
1591                         if (new_values == NULL) {
1592                                 ldb_module_oom(module);
1593                                 talloc_free(tmp_ctx);
1594                                 return LDB_ERR_OPERATIONS_ERROR;
1595                         }
1596                         ret = replmd_build_la_val(new_values, &new_values[num_new_values], dns[i].dsdb_dn,
1597                                                   invocation_id, seq_num, seq_num, now, 0, false);
1598                         if (ret != LDB_SUCCESS) {
1599                                 talloc_free(tmp_ctx);
1600                                 return ret;
1601                         }
1602                         num_new_values++;
1603                 } else {
1604                         /* this is only allowed if the GUID was
1605                            previously deleted. */
1606                         uint32_t rmd_flags = dsdb_dn_rmd_flags(p->dsdb_dn->dn);
1607
1608                         if (!(rmd_flags & DSDB_RMD_FLAG_DELETED)) {
1609                                 ldb_asprintf_errstring(ldb, "Attribute %s already exists for target GUID %s",
1610                                                        el->name, GUID_string(tmp_ctx, p->guid));
1611                                 talloc_free(tmp_ctx);
1612                                 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
1613                         }
1614                         ret = replmd_update_la_val(old_el->values, p->v, dns[i].dsdb_dn, p->dsdb_dn,
1615                                                    invocation_id, seq_num, seq_num, now, 0, false);
1616                         if (ret != LDB_SUCCESS) {
1617                                 talloc_free(tmp_ctx);
1618                                 return ret;
1619                         }
1620                 }
1621
1622                 ret = replmd_add_backlink(module, schema, msg_guid, dns[i].guid, true, schema_attr, true);
1623                 if (ret != LDB_SUCCESS) {
1624                         talloc_free(tmp_ctx);
1625                         return ret;
1626                 }
1627         }
1628
1629         /* add the new ones on to the end of the old values, constructing a new el->values */
1630         el->values = talloc_realloc(msg->elements, old_el?old_el->values:NULL,
1631                                     struct ldb_val,
1632                                     old_num_values+num_new_values);
1633         if (el->values == NULL) {
1634                 ldb_module_oom(module);
1635                 return LDB_ERR_OPERATIONS_ERROR;
1636         }
1637
1638         memcpy(&el->values[old_num_values], new_values, num_new_values*sizeof(struct ldb_val));
1639         el->num_values = old_num_values + num_new_values;
1640
1641         talloc_steal(msg->elements, el->values);
1642         talloc_steal(el->values, new_values);
1643
1644         talloc_free(tmp_ctx);
1645
1646         /* we now tell the backend to replace all existing values
1647            with the one we have constructed */
1648         el->flags = LDB_FLAG_MOD_REPLACE;
1649
1650         return LDB_SUCCESS;
1651 }
1652
1653
1654 /*
1655   handle deleting all active linked attributes
1656  */
1657 static int replmd_modify_la_delete(struct ldb_module *module,
1658                                    const struct dsdb_schema *schema,
1659                                    struct ldb_message *msg,
1660                                    struct ldb_message_element *el,
1661                                    struct ldb_message_element *old_el,
1662                                    const struct dsdb_attribute *schema_attr,
1663                                    uint64_t seq_num,
1664                                    time_t t,
1665                                    struct GUID *msg_guid)
1666 {
1667         unsigned int i;
1668         struct parsed_dn *dns, *old_dns;
1669         TALLOC_CTX *tmp_ctx = talloc_new(msg);
1670         int ret;
1671         const struct GUID *invocation_id;
1672         struct ldb_context *ldb = ldb_module_get_ctx(module);
1673         NTTIME now;
1674
1675         unix_to_nt_time(&now, t);
1676
1677         /* check if there is nothing to delete */
1678         if ((!old_el || old_el->num_values == 0) &&
1679             el->num_values == 0) {
1680                 return LDB_SUCCESS;
1681         }
1682
1683         if (!old_el || old_el->num_values == 0) {
1684                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1685         }
1686
1687         ret = get_parsed_dns(module, tmp_ctx, el, &dns, schema_attr->syntax->ldap_oid);
1688         if (ret != LDB_SUCCESS) {
1689                 talloc_free(tmp_ctx);
1690                 return ret;
1691         }
1692
1693         ret = get_parsed_dns(module, tmp_ctx, old_el, &old_dns, schema_attr->syntax->ldap_oid);
1694         if (ret != LDB_SUCCESS) {
1695                 talloc_free(tmp_ctx);
1696                 return ret;
1697         }
1698
1699         invocation_id = samdb_ntds_invocation_id(ldb);
1700         if (!invocation_id) {
1701                 return LDB_ERR_OPERATIONS_ERROR;
1702         }
1703
1704         ret = replmd_check_upgrade_links(old_dns, old_el->num_values, invocation_id);
1705         if (ret != LDB_SUCCESS) {
1706                 talloc_free(tmp_ctx);
1707                 return ret;
1708         }
1709
1710         el->values = NULL;
1711
1712         /* see if we are being asked to delete any links that
1713            don't exist or are already deleted */
1714         for (i=0; i<el->num_values; i++) {
1715                 struct parsed_dn *p = &dns[i];
1716                 struct parsed_dn *p2;
1717                 uint32_t rmd_flags;
1718
1719                 p2 = parsed_dn_find(old_dns, old_el->num_values, p->guid, NULL);
1720                 if (!p2) {
1721                         ldb_asprintf_errstring(ldb, "Attribute %s doesn't exist for target GUID %s",
1722                                                el->name, GUID_string(tmp_ctx, p->guid));
1723                         return LDB_ERR_NO_SUCH_ATTRIBUTE;
1724                 }
1725                 rmd_flags = dsdb_dn_rmd_flags(p2->dsdb_dn->dn);
1726                 if (rmd_flags & DSDB_RMD_FLAG_DELETED) {
1727                         ldb_asprintf_errstring(ldb, "Attribute %s already deleted for target GUID %s",
1728                                                el->name, GUID_string(tmp_ctx, p->guid));
1729                         return LDB_ERR_NO_SUCH_ATTRIBUTE;
1730                 }
1731         }
1732
1733         /* for each new value, see if it exists already with the same GUID
1734            if it is not already deleted and matches the delete list then delete it
1735         */
1736         for (i=0; i<old_el->num_values; i++) {
1737                 struct parsed_dn *p = &old_dns[i];
1738                 uint32_t rmd_flags;
1739
1740                 if (el->num_values && parsed_dn_find(dns, el->num_values, p->guid, NULL) == NULL) {
1741                         continue;
1742                 }
1743
1744                 rmd_flags = dsdb_dn_rmd_flags(p->dsdb_dn->dn);
1745                 if (rmd_flags & DSDB_RMD_FLAG_DELETED) continue;
1746
1747                 ret = replmd_update_la_val(old_el->values, p->v, p->dsdb_dn, p->dsdb_dn,
1748                                            invocation_id, seq_num, seq_num, now, 0, true);
1749                 if (ret != LDB_SUCCESS) {
1750                         talloc_free(tmp_ctx);
1751                         return ret;
1752                 }
1753
1754                 ret = replmd_add_backlink(module, schema, msg_guid, old_dns[i].guid, false, schema_attr, true);
1755                 if (ret != LDB_SUCCESS) {
1756                         talloc_free(tmp_ctx);
1757                         return ret;
1758                 }
1759         }
1760
1761         el->values = talloc_steal(msg->elements, old_el->values);
1762         el->num_values = old_el->num_values;
1763
1764         talloc_free(tmp_ctx);
1765
1766         /* we now tell the backend to replace all existing values
1767            with the one we have constructed */
1768         el->flags = LDB_FLAG_MOD_REPLACE;
1769
1770         return LDB_SUCCESS;
1771 }
1772
1773 /*
1774   handle replacing a linked attribute
1775  */
1776 static int replmd_modify_la_replace(struct ldb_module *module,
1777                                     const struct dsdb_schema *schema,
1778                                     struct ldb_message *msg,
1779                                     struct ldb_message_element *el,
1780                                     struct ldb_message_element *old_el,
1781                                     const struct dsdb_attribute *schema_attr,
1782                                     uint64_t seq_num,
1783                                     time_t t,
1784                                     struct GUID *msg_guid)
1785 {
1786         unsigned int i;
1787         struct parsed_dn *dns, *old_dns;
1788         TALLOC_CTX *tmp_ctx = talloc_new(msg);
1789         int ret;
1790         const struct GUID *invocation_id;
1791         struct ldb_context *ldb = ldb_module_get_ctx(module);
1792         struct ldb_val *new_values = NULL;
1793         unsigned int num_new_values = 0;
1794         unsigned int old_num_values = old_el?old_el->num_values:0;
1795         NTTIME now;
1796
1797         unix_to_nt_time(&now, t);
1798
1799         /* check if there is nothing to replace */
1800         if ((!old_el || old_el->num_values == 0) &&
1801             el->num_values == 0) {
1802                 return LDB_SUCCESS;
1803         }
1804
1805         ret = get_parsed_dns(module, tmp_ctx, el, &dns, schema_attr->syntax->ldap_oid);
1806         if (ret != LDB_SUCCESS) {
1807                 talloc_free(tmp_ctx);
1808                 return ret;
1809         }
1810
1811         ret = get_parsed_dns(module, tmp_ctx, old_el, &old_dns, schema_attr->syntax->ldap_oid);
1812         if (ret != LDB_SUCCESS) {
1813                 talloc_free(tmp_ctx);
1814                 return ret;
1815         }
1816
1817         invocation_id = samdb_ntds_invocation_id(ldb);
1818         if (!invocation_id) {
1819                 return LDB_ERR_OPERATIONS_ERROR;
1820         }
1821
1822         ret = replmd_check_upgrade_links(old_dns, old_num_values, invocation_id);
1823         if (ret != LDB_SUCCESS) {
1824                 talloc_free(tmp_ctx);
1825                 return ret;
1826         }
1827
1828         /* mark all the old ones as deleted */
1829         for (i=0; i<old_num_values; i++) {
1830                 struct parsed_dn *old_p = &old_dns[i];
1831                 struct parsed_dn *p;
1832                 uint32_t rmd_flags = dsdb_dn_rmd_flags(old_p->dsdb_dn->dn);
1833
1834                 if (rmd_flags & DSDB_RMD_FLAG_DELETED) continue;
1835
1836                 ret = replmd_add_backlink(module, schema, msg_guid, old_dns[i].guid, false, schema_attr, false);
1837                 if (ret != LDB_SUCCESS) {
1838                         talloc_free(tmp_ctx);
1839                         return ret;
1840                 }
1841
1842                 p = parsed_dn_find(dns, el->num_values, old_p->guid, NULL);
1843                 if (p) {
1844                         /* we don't delete it if we are re-adding it */
1845                         continue;
1846                 }
1847
1848                 ret = replmd_update_la_val(old_el->values, old_p->v, old_p->dsdb_dn, old_p->dsdb_dn,
1849                                            invocation_id, seq_num, seq_num, now, 0, true);
1850                 if (ret != LDB_SUCCESS) {
1851                         talloc_free(tmp_ctx);
1852                         return ret;
1853                 }
1854         }
1855
1856         /* for each new value, either update its meta-data, or add it
1857          * to old_el
1858         */
1859         for (i=0; i<el->num_values; i++) {
1860                 struct parsed_dn *p = &dns[i], *old_p;
1861
1862                 if (old_dns &&
1863                     (old_p = parsed_dn_find(old_dns,
1864                                             old_num_values, p->guid, NULL)) != NULL) {
1865                         /* update in place */
1866                         ret = replmd_update_la_val(old_el->values, old_p->v, old_p->dsdb_dn,
1867                                                    old_p->dsdb_dn, invocation_id,
1868                                                    seq_num, seq_num, now, 0, false);
1869                         if (ret != LDB_SUCCESS) {
1870                                 talloc_free(tmp_ctx);
1871                                 return ret;
1872                         }
1873                 } else {
1874                         /* add a new one */
1875                         new_values = talloc_realloc(tmp_ctx, new_values, struct ldb_val,
1876                                                     num_new_values+1);
1877                         if (new_values == NULL) {
1878                                 ldb_module_oom(module);
1879                                 talloc_free(tmp_ctx);
1880                                 return LDB_ERR_OPERATIONS_ERROR;
1881                         }
1882                         ret = replmd_build_la_val(new_values, &new_values[num_new_values], dns[i].dsdb_dn,
1883                                                   invocation_id, seq_num, seq_num, now, 0, false);
1884                         if (ret != LDB_SUCCESS) {
1885                                 talloc_free(tmp_ctx);
1886                                 return ret;
1887                         }
1888                         num_new_values++;
1889                 }
1890
1891                 ret = replmd_add_backlink(module, schema, msg_guid, dns[i].guid, true, schema_attr, false);
1892                 if (ret != LDB_SUCCESS) {
1893                         talloc_free(tmp_ctx);
1894                         return ret;
1895                 }
1896         }
1897
1898         /* add the new values to the end of old_el */
1899         if (num_new_values != 0) {
1900                 el->values = talloc_realloc(msg->elements, old_el?old_el->values:NULL,
1901                                             struct ldb_val, old_num_values+num_new_values);
1902                 if (el->values == NULL) {
1903                         ldb_module_oom(module);
1904                         return LDB_ERR_OPERATIONS_ERROR;
1905                 }
1906                 memcpy(&el->values[old_num_values], &new_values[0],
1907                        sizeof(struct ldb_val)*num_new_values);
1908                 el->num_values = old_num_values + num_new_values;
1909                 talloc_steal(msg->elements, new_values);
1910         } else {
1911                 el->values = old_el->values;
1912                 el->num_values = old_el->num_values;
1913                 talloc_steal(msg->elements, el->values);
1914         }
1915
1916         talloc_free(tmp_ctx);
1917
1918         /* we now tell the backend to replace all existing values
1919            with the one we have constructed */
1920         el->flags = LDB_FLAG_MOD_REPLACE;
1921
1922         return LDB_SUCCESS;
1923 }
1924
1925
1926 /*
1927   handle linked attributes in modify requests
1928  */
1929 static int replmd_modify_handle_linked_attribs(struct ldb_module *module,
1930                                                struct ldb_message *msg,
1931                                                uint64_t seq_num, time_t t)
1932 {
1933         struct ldb_result *res;
1934         unsigned int i;
1935         int ret;
1936         struct ldb_context *ldb = ldb_module_get_ctx(module);
1937         struct ldb_message *old_msg;
1938
1939         const struct dsdb_schema *schema;
1940         struct GUID old_guid;
1941
1942         if (seq_num == 0) {
1943                 /* there the replmd_update_rpmd code has already
1944                  * checked and saw that there are no linked
1945                  * attributes */
1946                 return LDB_SUCCESS;
1947         }
1948
1949 #if !W2K3_LINKED_ATTRIBUTES
1950         return LDB_SUCCESS;
1951 #endif
1952
1953         if (dsdb_functional_level(ldb) == DS_DOMAIN_FUNCTION_2000) {
1954                 /* don't do anything special for linked attributes */
1955                 return LDB_SUCCESS;
1956         }
1957
1958         ret = dsdb_module_search_dn(module, msg, &res, msg->dn, NULL,
1959                                     DSDB_SEARCH_SHOW_DELETED |
1960                                     DSDB_SEARCH_REVEAL_INTERNALS |
1961                                     DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
1962         if (ret != LDB_SUCCESS) {
1963                 return ret;
1964         }
1965         schema = dsdb_get_schema(ldb, res);
1966         if (!schema) {
1967                 return LDB_ERR_OPERATIONS_ERROR;
1968         }
1969
1970         old_msg = res->msgs[0];
1971
1972         old_guid = samdb_result_guid(old_msg, "objectGUID");
1973
1974         for (i=0; i<msg->num_elements; i++) {
1975                 struct ldb_message_element *el = &msg->elements[i];
1976                 struct ldb_message_element *old_el, *new_el;
1977                 const struct dsdb_attribute *schema_attr
1978                         = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
1979                 if (!schema_attr) {
1980                         ldb_asprintf_errstring(ldb,
1981                                                "attribute %s is not a valid attribute in schema", el->name);
1982                         return LDB_ERR_OBJECT_CLASS_VIOLATION;
1983                 }
1984                 if (schema_attr->linkID == 0) {
1985                         continue;
1986                 }
1987                 if ((schema_attr->linkID & 1) == 1) {
1988                         /* Odd is for the target.  Illegal to modify */
1989                         ldb_asprintf_errstring(ldb,
1990                                                "attribute %s must not be modified directly, it is a linked attribute", el->name);
1991                         return LDB_ERR_UNWILLING_TO_PERFORM;
1992                 }
1993                 old_el = ldb_msg_find_element(old_msg, el->name);
1994                 switch (el->flags & LDB_FLAG_MOD_MASK) {
1995                 case LDB_FLAG_MOD_REPLACE:
1996                         ret = replmd_modify_la_replace(module, schema, msg, el, old_el, schema_attr, seq_num, t, &old_guid);
1997                         break;
1998                 case LDB_FLAG_MOD_DELETE:
1999                         ret = replmd_modify_la_delete(module, schema, msg, el, old_el, schema_attr, seq_num, t, &old_guid);
2000                         break;
2001                 case LDB_FLAG_MOD_ADD:
2002                         ret = replmd_modify_la_add(module, schema, msg, el, old_el, schema_attr, seq_num, t, &old_guid);
2003                         break;
2004                 default:
2005                         ldb_asprintf_errstring(ldb,
2006                                                "invalid flags 0x%x for %s linked attribute",
2007                                                el->flags, el->name);
2008                         return LDB_ERR_UNWILLING_TO_PERFORM;
2009                 }
2010                 if (ret != LDB_SUCCESS) {
2011                         return ret;
2012                 }
2013                 if (old_el) {
2014                         ldb_msg_remove_attr(old_msg, el->name);
2015                 }
2016                 ldb_msg_add_empty(old_msg, el->name, 0, &new_el);
2017                 new_el->num_values = el->num_values;
2018                 new_el->values = talloc_steal(msg->elements, el->values);
2019
2020                 /* TODO: this relises a bit too heavily on the exact
2021                    behaviour of ldb_msg_find_element and
2022                    ldb_msg_remove_element */
2023                 old_el = ldb_msg_find_element(msg, el->name);
2024                 if (old_el != el) {
2025                         ldb_msg_remove_element(msg, old_el);
2026                         i--;
2027                 }
2028         }
2029
2030         talloc_free(res);
2031         return ret;
2032 }
2033
2034
2035
2036 static int replmd_modify(struct ldb_module *module, struct ldb_request *req)
2037 {
2038         struct ldb_context *ldb;
2039         struct replmd_replicated_request *ac;
2040         struct ldb_request *down_req;
2041         struct ldb_message *msg;
2042         time_t t = time(NULL);
2043         int ret;
2044         bool is_urgent = false;
2045
2046         /* do not manipulate our control entries */
2047         if (ldb_dn_is_special(req->op.mod.message->dn)) {
2048                 return ldb_next_request(module, req);
2049         }
2050
2051         ldb = ldb_module_get_ctx(module);
2052
2053         ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_modify\n");
2054
2055         ac = replmd_ctx_init(module, req);
2056         if (!ac) {
2057                 return LDB_ERR_OPERATIONS_ERROR;
2058         }
2059
2060         /* we have to copy the message as the caller might have it as a const */
2061         msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
2062         if (msg == NULL) {
2063                 ldb_oom(ldb);
2064                 talloc_free(ac);
2065                 return LDB_ERR_OPERATIONS_ERROR;
2066         }
2067
2068         ldb_msg_remove_attr(msg, "whenChanged");
2069         ldb_msg_remove_attr(msg, "uSNChanged");
2070
2071         ret = replmd_update_rpmd(module, ac->schema, msg, &ac->seq_num, t, &is_urgent);
2072         if (ret != LDB_SUCCESS) {
2073                 talloc_free(ac);
2074                 return ret;
2075         }
2076
2077         ret = replmd_modify_handle_linked_attribs(module, msg, ac->seq_num, t);
2078         if (ret != LDB_SUCCESS) {
2079                 talloc_free(ac);
2080                 return ret;
2081         }
2082
2083         /* TODO:
2084          * - replace the old object with the newly constructed one
2085          */
2086
2087         ac->is_urgent = is_urgent;
2088
2089         ret = ldb_build_mod_req(&down_req, ldb, ac,
2090                                 msg,
2091                                 req->controls,
2092                                 ac, replmd_op_callback,
2093                                 req);
2094         if (ret != LDB_SUCCESS) {
2095                 talloc_free(ac);
2096                 return ret;
2097         }
2098         talloc_steal(down_req, msg);
2099
2100         /* we only change whenChanged and uSNChanged if the seq_num
2101            has changed */
2102         if (ac->seq_num != 0) {
2103                 if (add_time_element(msg, "whenChanged", t) != LDB_SUCCESS) {
2104                         talloc_free(ac);
2105                         return ret;
2106                 }
2107
2108                 if (add_uint64_element(msg, "uSNChanged", ac->seq_num) != LDB_SUCCESS) {
2109                         talloc_free(ac);
2110                         return ret;
2111                 }
2112         }
2113
2114         /* go on with the call chain */
2115         return ldb_next_request(module, down_req);
2116 }
2117
2118 static int replmd_rename_callback(struct ldb_request *req, struct ldb_reply *ares);
2119
2120 /*
2121   handle a rename request
2122
2123   On a rename we need to do an extra ldb_modify which sets the
2124   whenChanged and uSNChanged attributes.  We do this in a callback after the success.
2125  */
2126 static int replmd_rename(struct ldb_module *module, struct ldb_request *req)
2127 {
2128         struct ldb_context *ldb;
2129         struct replmd_replicated_request *ac;
2130         int ret;
2131         struct ldb_request *down_req;
2132
2133         /* do not manipulate our control entries */
2134         if (ldb_dn_is_special(req->op.mod.message->dn)) {
2135                 return ldb_next_request(module, req);
2136         }
2137
2138         ldb = ldb_module_get_ctx(module);
2139
2140         ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_rename\n");
2141
2142         ac = replmd_ctx_init(module, req);
2143         if (!ac) {
2144                 return LDB_ERR_OPERATIONS_ERROR;
2145         }
2146         ret = ldb_build_rename_req(&down_req, ldb, ac,
2147                                    ac->req->op.rename.olddn,
2148                                    ac->req->op.rename.newdn,
2149                                    ac->req->controls,
2150                                    ac, replmd_rename_callback,
2151                                    ac->req);
2152
2153         if (ret != LDB_SUCCESS) {
2154                 talloc_free(ac);
2155                 return ret;
2156         }
2157
2158         /* go on with the call chain */
2159         return ldb_next_request(module, down_req);
2160 }
2161
2162 /* After the rename is compleated, update the whenchanged etc */
2163 static int replmd_rename_callback(struct ldb_request *req, struct ldb_reply *ares)
2164 {
2165         struct ldb_context *ldb;
2166         struct replmd_replicated_request *ac;
2167         struct ldb_request *down_req;
2168         struct ldb_message *msg;
2169         time_t t = time(NULL);
2170         int ret;
2171
2172         ac = talloc_get_type(req->context, struct replmd_replicated_request);
2173         ldb = ldb_module_get_ctx(ac->module);
2174
2175         if (ares->error != LDB_SUCCESS) {
2176                 return ldb_module_done(ac->req, ares->controls,
2177                                         ares->response, ares->error);
2178         }
2179
2180         if (ares->type != LDB_REPLY_DONE) {
2181                 ldb_set_errstring(ldb,
2182                                   "invalid ldb_reply_type in callback");
2183                 talloc_free(ares);
2184                 return ldb_module_done(ac->req, NULL, NULL,
2185                                         LDB_ERR_OPERATIONS_ERROR);
2186         }
2187
2188         /* Get a sequence number from the backend */
2189         ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &ac->seq_num);
2190         if (ret != LDB_SUCCESS) {
2191                 return ret;
2192         }
2193
2194         /* TODO:
2195          * - replace the old object with the newly constructed one
2196          */
2197
2198         msg = ldb_msg_new(ac);
2199         if (msg == NULL) {
2200                 ldb_oom(ldb);
2201                 return LDB_ERR_OPERATIONS_ERROR;
2202         }
2203
2204         msg->dn = ac->req->op.rename.newdn;
2205
2206         ret = ldb_build_mod_req(&down_req, ldb, ac,
2207                                 msg,
2208                                 req->controls,
2209                                 ac, replmd_op_callback,
2210                                 req);
2211
2212         if (ret != LDB_SUCCESS) {
2213                 talloc_free(ac);
2214                 return ret;
2215         }
2216         talloc_steal(down_req, msg);
2217
2218         if (add_time_element(msg, "whenChanged", t) != LDB_SUCCESS) {
2219                 talloc_free(ac);
2220                 return ret;
2221         }
2222         
2223         if (add_uint64_element(msg, "uSNChanged", ac->seq_num) != LDB_SUCCESS) {
2224                 talloc_free(ac);
2225                 return ret;
2226         }
2227
2228         /* go on with the call chain - do the modify after the rename */
2229         return ldb_next_request(ac->module, down_req);
2230 }
2231
2232 /*
2233    remove links from objects that point at this object when an object
2234    is deleted
2235  */
2236 static int replmd_delete_remove_link(struct ldb_module *module,
2237                                      const struct dsdb_schema *schema,
2238                                      struct ldb_dn *dn,
2239                                      struct ldb_message_element *el,
2240                                      const struct dsdb_attribute *sa)
2241 {
2242         unsigned int i;
2243         TALLOC_CTX *tmp_ctx = talloc_new(module);
2244         struct ldb_context *ldb = ldb_module_get_ctx(module);
2245
2246         for (i=0; i<el->num_values; i++) {
2247                 struct dsdb_dn *dsdb_dn;
2248                 NTSTATUS status;
2249                 int ret;
2250                 struct GUID guid2;
2251                 struct ldb_message *msg;
2252                 const struct dsdb_attribute *target_attr;
2253                 struct ldb_message_element *el2;
2254                 struct ldb_val dn_val;
2255
2256                 if (dsdb_dn_is_deleted_val(&el->values[i])) {
2257                         continue;
2258                 }
2259
2260                 dsdb_dn = dsdb_dn_parse(tmp_ctx, ldb, &el->values[i], sa->syntax->ldap_oid);
2261                 if (!dsdb_dn) {
2262                         talloc_free(tmp_ctx);
2263                         return LDB_ERR_OPERATIONS_ERROR;
2264                 }
2265
2266                 status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &guid2, "GUID");
2267                 if (!NT_STATUS_IS_OK(status)) {
2268                         talloc_free(tmp_ctx);
2269                         return LDB_ERR_OPERATIONS_ERROR;
2270                 }
2271
2272                 /* remove the link */
2273                 msg = ldb_msg_new(tmp_ctx);
2274                 if (!msg) {
2275                         ldb_module_oom(module);
2276                         talloc_free(tmp_ctx);
2277                         return LDB_ERR_OPERATIONS_ERROR;
2278                 }
2279
2280
2281                 msg->dn = dsdb_dn->dn;
2282
2283                 target_attr = dsdb_attribute_by_linkID(schema, sa->linkID ^ 1);
2284                 if (target_attr == NULL) {
2285                         continue;
2286                 }
2287
2288                 ret = ldb_msg_add_empty(msg, target_attr->lDAPDisplayName, LDB_FLAG_MOD_DELETE, &el2);
2289                 if (ret != LDB_SUCCESS) {
2290                         ldb_module_oom(module);
2291                         talloc_free(tmp_ctx);
2292                         return LDB_ERR_OPERATIONS_ERROR;
2293                 }
2294                 dn_val = data_blob_string_const(ldb_dn_get_linearized(dn));
2295                 el2->values = &dn_val;
2296                 el2->num_values = 1;
2297
2298                 ret = dsdb_module_modify(module, msg, DSDB_FLAG_OWN_MODULE);
2299                 if (ret != LDB_SUCCESS) {
2300                         talloc_free(tmp_ctx);
2301                         return ret;
2302                 }
2303         }
2304         talloc_free(tmp_ctx);
2305         return LDB_SUCCESS;
2306 }
2307
2308
2309 /*
2310   handle update of replication meta data for deletion of objects
2311
2312   This also handles the mapping of delete to a rename operation
2313   to allow deletes to be replicated.
2314  */
2315 static int replmd_delete(struct ldb_module *module, struct ldb_request *req)
2316 {
2317         int ret = LDB_ERR_OTHER;
2318         bool retb;
2319         struct ldb_dn *old_dn, *new_dn;
2320         const char *rdn_name;
2321         const struct ldb_val *rdn_value, *new_rdn_value;
2322         struct GUID guid;
2323         struct ldb_context *ldb = ldb_module_get_ctx(module);
2324         const struct dsdb_schema *schema;
2325         struct ldb_message *msg, *old_msg;
2326         struct ldb_message_element *el;
2327         TALLOC_CTX *tmp_ctx;
2328         struct ldb_result *res, *parent_res;
2329         const char *preserved_attrs[] = {
2330                 /* yes, this really is a hard coded list. See MS-ADTS
2331                    section 3.1.1.5.5.1.1 */
2332                 "nTSecurityDescriptor", "attributeID", "attributeSyntax", "dNReferenceUpdate", "dNSHostName",
2333                 "flatName", "governsID", "groupType", "instanceType", "lDAPDisplayName", "legacyExchangeDN",
2334                 "isDeleted", "isRecycled", "lastKnownParent", "msDS-LastKnownRDN", "mS-DS-CreatorSID",
2335                 "mSMQOwnerID", "nCName", "objectClass", "distinguishedName", "objectGUID", "objectSid",
2336                 "oMSyntax", "proxiedObjectName", "name", "replPropertyMetaData", "sAMAccountName",
2337                 "securityIdentifier", "sIDHistory", "subClassOf", "systemFlags", "trustPartner", "trustDirection",
2338                 "trustType", "trustAttributes", "userAccountControl", "uSNChanged", "uSNCreated", "whenCreated",
2339                 "whenChanged", NULL};
2340         unsigned int i, el_count = 0;
2341         enum deletion_state { OBJECT_NOT_DELETED=1, OBJECT_DELETED=2, OBJECT_RECYCLED=3,
2342                                                 OBJECT_TOMBSTONE=4, OBJECT_REMOVED=5 };
2343         enum deletion_state deletion_state, next_deletion_state;
2344         bool enabled;
2345
2346         if (ldb_dn_is_special(req->op.del.dn)) {
2347                 return ldb_next_request(module, req);
2348         }
2349
2350         tmp_ctx = talloc_new(ldb);
2351         if (!tmp_ctx) {
2352                 ldb_oom(ldb);
2353                 return LDB_ERR_OPERATIONS_ERROR;
2354         }
2355         
2356         schema = dsdb_get_schema(ldb, tmp_ctx);
2357         if (!schema) {
2358                 return LDB_ERR_OPERATIONS_ERROR;
2359         }
2360
2361         old_dn = ldb_dn_copy(tmp_ctx, req->op.del.dn);
2362
2363         /* we need the complete msg off disk, so we can work out which
2364            attributes need to be removed */
2365         ret = dsdb_module_search_dn(module, tmp_ctx, &res, old_dn, NULL,
2366                                     DSDB_SEARCH_SHOW_DELETED |
2367                                     DSDB_SEARCH_REVEAL_INTERNALS |
2368                                     DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT);
2369         if (ret != LDB_SUCCESS) {
2370                 talloc_free(tmp_ctx);
2371                 return ret;
2372         }
2373         old_msg = res->msgs[0];
2374
2375
2376         ret = dsdb_recyclebin_enabled(module, &enabled);
2377         if (ret != LDB_SUCCESS) {
2378                 talloc_free(tmp_ctx);
2379                 return ret;
2380         }
2381
2382         if (ldb_msg_check_string_attribute(old_msg, "isDeleted", "TRUE")) {
2383                 if (!enabled) {
2384                         deletion_state = OBJECT_TOMBSTONE;
2385                         next_deletion_state = OBJECT_REMOVED;
2386                 } else if (ldb_msg_check_string_attribute(old_msg, "isRecycled", "TRUE")) {
2387                         deletion_state = OBJECT_RECYCLED;
2388                         next_deletion_state = OBJECT_REMOVED;
2389                 } else {
2390                         deletion_state = OBJECT_DELETED;
2391                         next_deletion_state = OBJECT_RECYCLED;
2392                 }
2393         } else {
2394                 deletion_state = OBJECT_NOT_DELETED;
2395                 if (enabled) {
2396                         next_deletion_state = OBJECT_DELETED;
2397                 } else {
2398                         next_deletion_state = OBJECT_TOMBSTONE;
2399                 }
2400         }
2401
2402         if (next_deletion_state == OBJECT_REMOVED) {
2403                 struct auth_session_info *session_info =
2404                                 (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
2405                 if (security_session_user_level(session_info) != SECURITY_SYSTEM) {
2406                         ldb_asprintf_errstring(ldb, "Refusing to delete deleted object %s",
2407                                         ldb_dn_get_linearized(old_msg->dn));
2408                         return LDB_ERR_UNWILLING_TO_PERFORM;
2409                 }
2410
2411                 /* it is already deleted - really remove it this time */
2412                 talloc_free(tmp_ctx);
2413                 return ldb_next_request(module, req);
2414         }
2415
2416         rdn_name = ldb_dn_get_rdn_name(old_dn);
2417         rdn_value = ldb_dn_get_rdn_val(old_dn);
2418
2419         msg = ldb_msg_new(tmp_ctx);
2420         if (msg == NULL) {
2421                 ldb_module_oom(module);
2422                 talloc_free(tmp_ctx);
2423                 return LDB_ERR_OPERATIONS_ERROR;
2424         }
2425
2426         msg->dn = old_dn;
2427
2428         if (deletion_state == OBJECT_NOT_DELETED){
2429                 /* work out where we will be renaming this object to */
2430                 ret = dsdb_get_deleted_objects_dn(ldb, tmp_ctx, old_dn, &new_dn);
2431                 if (ret != LDB_SUCCESS) {
2432                         /* this is probably an attempted delete on a partition
2433                          * that doesn't allow delete operations, such as the
2434                          * schema partition */
2435                         ldb_asprintf_errstring(ldb, "No Deleted Objects container for DN %s",
2436                                                    ldb_dn_get_linearized(old_dn));
2437                         talloc_free(tmp_ctx);
2438                         return LDB_ERR_UNWILLING_TO_PERFORM;
2439                 }
2440
2441                 /* get the objects GUID from the search we just did */
2442                 guid = samdb_result_guid(old_msg, "objectGUID");
2443
2444                 /* Add a formatted child */
2445                 retb = ldb_dn_add_child_fmt(new_dn, "%s=%s\\0ADEL:%s",
2446                                                 rdn_name,
2447                                                 rdn_value->data,
2448                                                 GUID_string(tmp_ctx, &guid));
2449                 if (!retb) {
2450                         DEBUG(0,(__location__ ": Unable to add a formatted child to dn: %s",
2451                                         ldb_dn_get_linearized(new_dn)));
2452                         talloc_free(tmp_ctx);
2453                         return LDB_ERR_OPERATIONS_ERROR;
2454                 }
2455
2456                 ret = ldb_msg_add_string(msg, "isDeleted", "TRUE");
2457                 if (ret != LDB_SUCCESS) {
2458                         DEBUG(0,(__location__ ": Failed to add isDeleted string to the msg\n"));
2459                         ldb_module_oom(module);
2460                         talloc_free(tmp_ctx);
2461                         return ret;
2462                 }
2463                 msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
2464         }
2465
2466         /*
2467           now we need to modify the object in the following ways:
2468
2469           - add isDeleted=TRUE
2470           - update rDN and name, with new rDN
2471           - remove linked attributes
2472           - remove objectCategory and sAMAccountType
2473           - remove attribs not on the preserved list
2474              - preserved if in above list, or is rDN
2475           - remove all linked attribs from this object
2476           - remove all links from other objects to this object
2477           - add lastKnownParent
2478           - update replPropertyMetaData?
2479
2480           see MS-ADTS "Tombstone Requirements" section 3.1.1.5.5.1.1
2481          */
2482
2483         /* we need the storage form of the parent GUID */
2484         ret = dsdb_module_search_dn(module, tmp_ctx, &parent_res,
2485                                     ldb_dn_get_parent(tmp_ctx, old_dn), NULL,
2486                                     DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT |
2487                                     DSDB_SEARCH_REVEAL_INTERNALS|
2488                                     DSDB_SEARCH_SHOW_DELETED);
2489         if (ret != LDB_SUCCESS) {
2490                 talloc_free(tmp_ctx);
2491                 return ret;
2492         }
2493
2494         if (deletion_state == OBJECT_NOT_DELETED){
2495                 ret = ldb_msg_add_steal_string(msg, "lastKnownParent",
2496                                                    ldb_dn_get_extended_linearized(tmp_ctx, parent_res->msgs[0]->dn, 1));
2497                 if (ret != LDB_SUCCESS) {
2498                         DEBUG(0,(__location__ ": Failed to add lastKnownParent string to the msg\n"));
2499                         ldb_module_oom(module);
2500                         talloc_free(tmp_ctx);
2501                         return ret;
2502                 }
2503                 msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
2504         }
2505
2506         switch (next_deletion_state){
2507
2508         case OBJECT_DELETED:
2509
2510                 ret = ldb_msg_add_value(msg, "msDS-LastKnownRDN", rdn_value, NULL);
2511                 if (ret != LDB_SUCCESS) {
2512                         DEBUG(0,(__location__ ": Failed to add msDS-LastKnownRDN string to the msg\n"));
2513                         ldb_module_oom(module);
2514                         talloc_free(tmp_ctx);
2515                         return ret;
2516                 }
2517                 msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
2518
2519                 ret = ldb_msg_add_empty(msg, "objectCategory", LDB_FLAG_MOD_DELETE, NULL);
2520                 if (ret != LDB_SUCCESS) {
2521                         talloc_free(tmp_ctx);
2522                         ldb_module_oom(module);
2523                         return ret;
2524                 }
2525
2526                 ret = ldb_msg_add_empty(msg, "sAMAccountType", LDB_FLAG_MOD_DELETE, NULL);
2527                 if (ret != LDB_SUCCESS) {
2528                         talloc_free(tmp_ctx);
2529                         ldb_module_oom(module);
2530                         return ret;
2531                 }
2532
2533                 break;
2534
2535         case OBJECT_RECYCLED:
2536         case OBJECT_TOMBSTONE:
2537
2538                 /* we also mark it as recycled, meaning this object can't be
2539                    recovered (we are stripping its attributes) */
2540                 if (dsdb_functional_level(ldb) >= DS_DOMAIN_FUNCTION_2008_R2) {
2541                         ret = ldb_msg_add_string(msg, "isRecycled", "TRUE");
2542                         if (ret != LDB_SUCCESS) {
2543                                 DEBUG(0,(__location__ ": Failed to add isRecycled string to the msg\n"));
2544                                 ldb_module_oom(module);
2545                                 talloc_free(tmp_ctx);
2546                                 return ret;
2547                         }
2548                         msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
2549                 }
2550
2551                 /* work out which of the old attributes we will be removing */
2552                 for (i=0; i<old_msg->num_elements; i++) {
2553                         const struct dsdb_attribute *sa;
2554                         el = &old_msg->elements[i];
2555                         sa = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
2556                         if (!sa) {
2557                                 talloc_free(tmp_ctx);
2558                                 return LDB_ERR_OPERATIONS_ERROR;
2559                         }
2560                         if (ldb_attr_cmp(el->name, rdn_name) == 0) {
2561                                 /* don't remove the rDN */
2562                                 continue;
2563                         }
2564                         if (sa->linkID && sa->linkID & 1) {
2565                         ret = replmd_delete_remove_link(module, schema, old_dn, el, sa);
2566                                 if (ret != LDB_SUCCESS) {
2567                                         talloc_free(tmp_ctx);
2568                                         return LDB_ERR_OPERATIONS_ERROR;
2569                                 }
2570                                 continue;
2571                         }
2572                         if (!sa->linkID && ldb_attr_in_list(preserved_attrs, el->name)) {
2573                                 continue;
2574                         }
2575                         ret = ldb_msg_add_empty(msg, el->name, LDB_FLAG_MOD_DELETE, &el);
2576                         if (ret != LDB_SUCCESS) {
2577                                 talloc_free(tmp_ctx);
2578                                 ldb_module_oom(module);
2579                                 return ret;
2580                         }
2581                 }
2582                 break;
2583
2584         default:
2585                 break;
2586         }
2587
2588         if (deletion_state == OBJECT_NOT_DELETED) {
2589                 /* work out what the new rdn value is, for updating the
2590                    rDN and name fields */
2591                 new_rdn_value = ldb_dn_get_rdn_val(new_dn);
2592
2593                 ret = ldb_msg_add_value(msg, strlower_talloc(tmp_ctx, rdn_name), new_rdn_value, &el);
2594                 if (ret != LDB_SUCCESS) {
2595                         talloc_free(tmp_ctx);
2596                         return ret;
2597                 }
2598                 el->flags = LDB_FLAG_MOD_REPLACE;
2599
2600                 el = ldb_msg_find_element(old_msg, "name");
2601                 if (el) {
2602                         ret = ldb_msg_add_value(msg, "name", new_rdn_value, &el);
2603                         if (ret != LDB_SUCCESS) {
2604                                 talloc_free(tmp_ctx);
2605                                 return ret;
2606                         }
2607                         el->flags = LDB_FLAG_MOD_REPLACE;
2608                 }
2609         }
2610
2611         ret = dsdb_module_modify(module, msg, DSDB_FLAG_OWN_MODULE);
2612         if (ret != LDB_SUCCESS) {
2613                 ldb_asprintf_errstring(ldb, "replmd_delete: Failed to modify object %s in delete - %s",
2614                                        ldb_dn_get_linearized(old_dn), ldb_errstring(ldb));
2615                 talloc_free(tmp_ctx);
2616                 return ret;
2617         }
2618
2619         if (deletion_state == OBJECT_NOT_DELETED) {
2620                 /* now rename onto the new DN */
2621                 ret = dsdb_module_rename(module, old_dn, new_dn, 0);
2622                 if (ret != LDB_SUCCESS){
2623                         DEBUG(0,(__location__ ": Failed to rename object from '%s' to '%s' - %s\n",
2624                                  ldb_dn_get_linearized(old_dn),
2625                                  ldb_dn_get_linearized(new_dn),
2626                                  ldb_errstring(ldb)));
2627                         talloc_free(tmp_ctx);
2628                         return ret;
2629                 }
2630         }
2631
2632         talloc_free(tmp_ctx);
2633
2634         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
2635 }
2636
2637
2638
2639 static int replmd_replicated_request_error(struct replmd_replicated_request *ar, int ret)
2640 {
2641         return ret;
2642 }
2643
2644 static int replmd_replicated_request_werror(struct replmd_replicated_request *ar, WERROR status)
2645 {
2646         int ret = LDB_ERR_OTHER;
2647         /* TODO: do some error mapping */
2648         return ret;
2649 }
2650
2651 static int replmd_replicated_apply_add(struct replmd_replicated_request *ar)
2652 {
2653         struct ldb_context *ldb;
2654         struct ldb_request *change_req;
2655         enum ndr_err_code ndr_err;
2656         struct ldb_message *msg;
2657         struct replPropertyMetaDataBlob *md;
2658         struct ldb_val md_value;
2659         unsigned int i;
2660         int ret;
2661
2662         /*
2663          * TODO: check if the parent object exist
2664          */
2665
2666         /*
2667          * TODO: handle the conflict case where an object with the
2668          *       same name exist
2669          */
2670
2671         ldb = ldb_module_get_ctx(ar->module);
2672         msg = ar->objs->objects[ar->index_current].msg;
2673         md = ar->objs->objects[ar->index_current].meta_data;
2674
2675         ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &ar->seq_num);
2676         if (ret != LDB_SUCCESS) {
2677                 return replmd_replicated_request_error(ar, ret);
2678         }
2679
2680         ret = ldb_msg_add_value(msg, "objectGUID", &ar->objs->objects[ar->index_current].guid_value, NULL);
2681         if (ret != LDB_SUCCESS) {
2682                 return replmd_replicated_request_error(ar, ret);
2683         }
2684
2685         ret = ldb_msg_add_string(msg, "whenChanged", ar->objs->objects[ar->index_current].when_changed);
2686         if (ret != LDB_SUCCESS) {
2687                 return replmd_replicated_request_error(ar, ret);
2688         }
2689
2690         ret = samdb_msg_add_uint64(ldb, msg, msg, "uSNCreated", ar->seq_num);
2691         if (ret != LDB_SUCCESS) {
2692                 return replmd_replicated_request_error(ar, ret);
2693         }
2694
2695         ret = samdb_msg_add_uint64(ldb, msg, msg, "uSNChanged", ar->seq_num);
2696         if (ret != LDB_SUCCESS) {
2697                 return replmd_replicated_request_error(ar, ret);
2698         }
2699
2700         /* remove any message elements that have zero values */
2701         for (i=0; i<msg->num_elements; i++) {
2702                 struct ldb_message_element *el = &msg->elements[i];
2703
2704                 if (el->num_values == 0) {
2705                         DEBUG(4,(__location__ ": Removing attribute %s with num_values==0\n",
2706                                  el->name));
2707                         memmove(el, el+1, sizeof(*el)*(msg->num_elements - (i+1)));
2708                         msg->num_elements--;
2709                         i--;
2710                         continue;
2711                 }
2712         }
2713         
2714         /*
2715          * the meta data array is already sorted by the caller
2716          */
2717         for (i=0; i < md->ctr.ctr1.count; i++) {
2718                 md->ctr.ctr1.array[i].local_usn = ar->seq_num;
2719         }
2720         ndr_err = ndr_push_struct_blob(&md_value, msg, 
2721                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
2722                                        md,
2723                                        (ndr_push_flags_fn_t)ndr_push_replPropertyMetaDataBlob);
2724         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2725                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
2726                 return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
2727         }
2728         ret = ldb_msg_add_value(msg, "replPropertyMetaData", &md_value, NULL);
2729         if (ret != LDB_SUCCESS) {
2730                 return replmd_replicated_request_error(ar, ret);
2731         }
2732
2733         replmd_ldb_message_sort(msg, ar->schema);
2734
2735         if (DEBUGLVL(4)) {
2736                 char *s = ldb_ldif_message_string(ldb, ar, LDB_CHANGETYPE_ADD, msg);
2737                 DEBUG(4, ("DRS replication add message:\n%s\n", s));
2738                 talloc_free(s);
2739         }
2740
2741         ret = ldb_build_add_req(&change_req,
2742                                 ldb,
2743                                 ar,
2744                                 msg,
2745                                 ar->controls,
2746                                 ar,
2747                                 replmd_op_callback,
2748                                 ar->req);
2749         if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
2750
2751         return ldb_next_request(ar->module, change_req);
2752 }
2753
2754 /*
2755    return true if an update is newer than an existing entry
2756    see section 5.11 of MS-ADTS
2757 */
2758 static bool replmd_update_is_newer(const struct GUID *current_invocation_id,
2759                                    const struct GUID *update_invocation_id,
2760                                    uint32_t current_version,
2761                                    uint32_t update_version,
2762                                    NTTIME current_change_time,
2763                                    NTTIME update_change_time)
2764 {
2765         if (update_version != current_version) {
2766                 return update_version > current_version;
2767         }
2768         if (update_change_time > current_change_time) {
2769                 return true;
2770         }
2771         if (update_change_time == current_change_time) {
2772                 return GUID_compare(update_invocation_id, current_invocation_id) > 0;
2773         }
2774         return false;
2775 }
2776
2777 static bool replmd_replPropertyMetaData1_is_newer(struct replPropertyMetaData1 *cur_m,
2778                                                   struct replPropertyMetaData1 *new_m)
2779 {
2780         return replmd_update_is_newer(&cur_m->originating_invocation_id,
2781                                       &new_m->originating_invocation_id,
2782                                       cur_m->version,
2783                                       new_m->version,
2784                                       cur_m->originating_change_time,
2785                                       new_m->originating_change_time);
2786 }
2787
2788 static int replmd_replicated_apply_merge(struct replmd_replicated_request *ar)
2789 {
2790         struct ldb_context *ldb;
2791         struct ldb_request *change_req;
2792         enum ndr_err_code ndr_err;
2793         struct ldb_message *msg;
2794         struct replPropertyMetaDataBlob *rmd;
2795         struct replPropertyMetaDataBlob omd;
2796         const struct ldb_val *omd_value;
2797         struct replPropertyMetaDataBlob nmd;
2798         struct ldb_val nmd_value;
2799         unsigned int i;
2800         uint32_t j,ni=0;
2801         unsigned int removed_attrs = 0;
2802         int ret;
2803
2804         ldb = ldb_module_get_ctx(ar->module);
2805         msg = ar->objs->objects[ar->index_current].msg;
2806         rmd = ar->objs->objects[ar->index_current].meta_data;
2807         ZERO_STRUCT(omd);
2808         omd.version = 1;
2809
2810         /*
2811          * TODO: check repl data is correct after a rename
2812          */
2813         if (ldb_dn_compare(msg->dn, ar->search_msg->dn) != 0) {
2814                 ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_replicated_request rename %s => %s\n",
2815                           ldb_dn_get_linearized(ar->search_msg->dn),
2816                           ldb_dn_get_linearized(msg->dn));
2817                 if (dsdb_module_rename(ar->module,
2818                                        ar->search_msg->dn, msg->dn,
2819                                        DSDB_FLAG_OWN_MODULE) != LDB_SUCCESS) {
2820                         ldb_debug(ldb, LDB_DEBUG_FATAL, "replmd_replicated_request rename %s => %s failed - %s\n",
2821                                   ldb_dn_get_linearized(ar->search_msg->dn),
2822                                   ldb_dn_get_linearized(msg->dn),
2823                                   ldb_errstring(ldb));
2824                         return replmd_replicated_request_werror(ar, WERR_DS_DRA_DB_ERROR);
2825                 }
2826         }
2827
2828         /* find existing meta data */
2829         omd_value = ldb_msg_find_ldb_val(ar->search_msg, "replPropertyMetaData");
2830         if (omd_value) {
2831                 ndr_err = ndr_pull_struct_blob(omd_value, ar,
2832                                                lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), &omd,
2833                                                (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
2834                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2835                         NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
2836                         return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
2837                 }
2838
2839                 if (omd.version != 1) {
2840                         return replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
2841                 }
2842         }
2843
2844         ZERO_STRUCT(nmd);
2845         nmd.version = 1;
2846         nmd.ctr.ctr1.count = omd.ctr.ctr1.count + rmd->ctr.ctr1.count;
2847         nmd.ctr.ctr1.array = talloc_array(ar,
2848                                           struct replPropertyMetaData1,
2849                                           nmd.ctr.ctr1.count);
2850         if (!nmd.ctr.ctr1.array) return replmd_replicated_request_werror(ar, WERR_NOMEM);
2851
2852         /* first copy the old meta data */
2853         for (i=0; i < omd.ctr.ctr1.count; i++) {
2854                 nmd.ctr.ctr1.array[ni]  = omd.ctr.ctr1.array[i];
2855                 ni++;
2856         }
2857
2858         /* now merge in the new meta data */
2859         for (i=0; i < rmd->ctr.ctr1.count; i++) {
2860                 bool found = false;
2861
2862                 for (j=0; j < ni; j++) {
2863                         bool cmp;
2864
2865                         if (rmd->ctr.ctr1.array[i].attid != nmd.ctr.ctr1.array[j].attid) {
2866                                 continue;
2867                         }
2868
2869                         cmp = replmd_replPropertyMetaData1_is_newer(&nmd.ctr.ctr1.array[j],
2870                                                                     &rmd->ctr.ctr1.array[i]);
2871                         if (cmp) {
2872                                 /* replace the entry */
2873                                 nmd.ctr.ctr1.array[j] = rmd->ctr.ctr1.array[i];
2874                                 found = true;
2875                                 break;
2876                         }
2877
2878                         if (rmd->ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType) {
2879                                 DEBUG(1,("Discarding older DRS attribute update to %s on %s from %s\n",
2880                                          msg->elements[i-removed_attrs].name,
2881                                          ldb_dn_get_linearized(msg->dn),
2882                                          GUID_string(ar, &rmd->ctr.ctr1.array[i].originating_invocation_id)));
2883                         }
2884
2885                         /* we don't want to apply this change so remove the attribute */
2886                         ldb_msg_remove_element(msg, &msg->elements[i-removed_attrs]);
2887                         removed_attrs++;
2888
2889                         found = true;
2890                         break;
2891                 }
2892
2893                 if (found) continue;
2894
2895                 nmd.ctr.ctr1.array[ni] = rmd->ctr.ctr1.array[i];
2896                 ni++;
2897         }
2898
2899         /*
2900          * finally correct the size of the meta_data array
2901          */
2902         nmd.ctr.ctr1.count = ni;
2903
2904         /*
2905          * the rdn attribute (the alias for the name attribute),
2906          * 'cn' for most objects is the last entry in the meta data array
2907          * we have stored
2908          *
2909          * sort the new meta data array
2910          */
2911         ret = replmd_replPropertyMetaDataCtr1_sort(&nmd.ctr.ctr1, ar->schema, msg->dn);
2912         if (ret != LDB_SUCCESS) {
2913                 return ret;
2914         }
2915
2916         /*
2917          * check if some replicated attributes left, otherwise skip the ldb_modify() call
2918          */
2919         if (msg->num_elements == 0) {
2920                 ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_replicated_apply_merge[%u]: skip replace\n",
2921                           ar->index_current);
2922
2923                 ar->index_current++;
2924                 return replmd_replicated_apply_next(ar);
2925         }
2926
2927         ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_replicated_apply_merge[%u]: replace %u attributes\n",
2928                   ar->index_current, msg->num_elements);
2929
2930         ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &ar->seq_num);
2931         if (ret != LDB_SUCCESS) {
2932                 return replmd_replicated_request_error(ar, ret);
2933         }
2934
2935         for (i=0; i<ni; i++) {
2936                 nmd.ctr.ctr1.array[i].local_usn = ar->seq_num;
2937         }
2938
2939         /* create the meta data value */
2940         ndr_err = ndr_push_struct_blob(&nmd_value, msg, 
2941                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
2942                                        &nmd,
2943                                        (ndr_push_flags_fn_t)ndr_push_replPropertyMetaDataBlob);
2944         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2945                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
2946                 return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
2947         }
2948
2949         /*
2950          * when we know that we'll modify the record, add the whenChanged, uSNChanged
2951          * and replPopertyMetaData attributes
2952          */
2953         ret = ldb_msg_add_string(msg, "whenChanged", ar->objs->objects[ar->index_current].when_changed);
2954         if (ret != LDB_SUCCESS) {
2955                 return replmd_replicated_request_error(ar, ret);
2956         }
2957         ret = samdb_msg_add_uint64(ldb, msg, msg, "uSNChanged", ar->seq_num);
2958         if (ret != LDB_SUCCESS) {
2959                 return replmd_replicated_request_error(ar, ret);
2960         }
2961         ret = ldb_msg_add_value(msg, "replPropertyMetaData", &nmd_value, NULL);
2962         if (ret != LDB_SUCCESS) {
2963                 return replmd_replicated_request_error(ar, ret);
2964         }
2965
2966         replmd_ldb_message_sort(msg, ar->schema);
2967
2968         /* we want to replace the old values */
2969         for (i=0; i < msg->num_elements; i++) {
2970                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
2971         }
2972
2973         if (DEBUGLVL(4)) {
2974                 char *s = ldb_ldif_message_string(ldb, ar, LDB_CHANGETYPE_MODIFY, msg);
2975                 DEBUG(4, ("DRS replication modify message:\n%s\n", s));
2976                 talloc_free(s);
2977         }
2978
2979         ret = ldb_build_mod_req(&change_req,
2980                                 ldb,
2981                                 ar,
2982                                 msg,
2983                                 ar->controls,
2984                                 ar,
2985                                 replmd_op_callback,
2986                                 ar->req);
2987         if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
2988
2989         return ldb_next_request(ar->module, change_req);
2990 }
2991
2992 static int replmd_replicated_apply_search_callback(struct ldb_request *req,
2993                                                    struct ldb_reply *ares)
2994 {
2995         struct replmd_replicated_request *ar = talloc_get_type(req->context,
2996                                                struct replmd_replicated_request);
2997         int ret;
2998
2999         if (!ares) {
3000                 return ldb_module_done(ar->req, NULL, NULL,
3001                                         LDB_ERR_OPERATIONS_ERROR);
3002         }
3003         if (ares->error != LDB_SUCCESS &&
3004             ares->error != LDB_ERR_NO_SUCH_OBJECT) {
3005                 return ldb_module_done(ar->req, ares->controls,
3006                                         ares->response, ares->error);
3007         }
3008
3009         switch (ares->type) {
3010         case LDB_REPLY_ENTRY:
3011                 ar->search_msg = talloc_steal(ar, ares->message);
3012                 break;
3013
3014         case LDB_REPLY_REFERRAL:
3015                 /* we ignore referrals */
3016                 break;
3017
3018         case LDB_REPLY_DONE:
3019                 if (ar->search_msg != NULL) {
3020                         ret = replmd_replicated_apply_merge(ar);
3021                 } else {
3022                         ret = replmd_replicated_apply_add(ar);
3023                 }
3024                 if (ret != LDB_SUCCESS) {
3025                         return ldb_module_done(ar->req, NULL, NULL, ret);
3026                 }
3027         }
3028
3029         talloc_free(ares);
3030         return LDB_SUCCESS;
3031 }
3032
3033 static int replmd_replicated_uptodate_vector(struct replmd_replicated_request *ar);
3034
3035 static int replmd_replicated_apply_next(struct replmd_replicated_request *ar)
3036 {
3037         struct ldb_context *ldb;
3038         int ret;
3039         char *tmp_str;
3040         char *filter;
3041         struct ldb_request *search_req;
3042         struct ldb_search_options_control *options;
3043
3044         if (ar->index_current >= ar->objs->num_objects) {
3045                 /* done with it, go to next stage */
3046                 return replmd_replicated_uptodate_vector(ar);
3047         }
3048
3049         ldb = ldb_module_get_ctx(ar->module);
3050         ar->search_msg = NULL;
3051
3052         tmp_str = ldb_binary_encode(ar, ar->objs->objects[ar->index_current].guid_value);
3053         if (!tmp_str) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3054
3055         filter = talloc_asprintf(ar, "(objectGUID=%s)", tmp_str);
3056         if (!filter) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3057         talloc_free(tmp_str);
3058
3059         ret = ldb_build_search_req(&search_req,
3060                                    ldb,
3061                                    ar,
3062                                    NULL,
3063                                    LDB_SCOPE_SUBTREE,
3064                                    filter,
3065                                    NULL,
3066                                    NULL,
3067                                    ar,
3068                                    replmd_replicated_apply_search_callback,
3069                                    ar->req);
3070
3071         ret = ldb_request_add_control(search_req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3072         if (ret != LDB_SUCCESS) {
3073                 return ret;
3074         }
3075
3076         /* we need to cope with cross-partition links, so search for
3077            the GUID over all partitions */
3078         options = talloc(search_req, struct ldb_search_options_control);
3079         if (options == NULL) {
3080                 DEBUG(0, (__location__ ": out of memory\n"));
3081                 return LDB_ERR_OPERATIONS_ERROR;
3082         }
3083         options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3084
3085         ret = ldb_request_add_control(search_req,
3086                                       LDB_CONTROL_SEARCH_OPTIONS_OID,
3087                                       true, options);
3088         if (ret != LDB_SUCCESS) {
3089                 return ret;
3090         }
3091
3092         if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
3093
3094         return ldb_next_request(ar->module, search_req);
3095 }
3096
3097 static int replmd_replicated_uptodate_modify_callback(struct ldb_request *req,
3098                                                       struct ldb_reply *ares)
3099 {
3100         struct ldb_context *ldb;
3101         struct replmd_replicated_request *ar = talloc_get_type(req->context,
3102                                                struct replmd_replicated_request);
3103         ldb = ldb_module_get_ctx(ar->module);
3104
3105         if (!ares) {
3106                 return ldb_module_done(ar->req, NULL, NULL,
3107                                         LDB_ERR_OPERATIONS_ERROR);
3108         }
3109         if (ares->error != LDB_SUCCESS) {
3110                 return ldb_module_done(ar->req, ares->controls,
3111                                         ares->response, ares->error);
3112         }
3113
3114         if (ares->type != LDB_REPLY_DONE) {
3115                 ldb_set_errstring(ldb, "Invalid reply type\n!");
3116                 return ldb_module_done(ar->req, NULL, NULL,
3117                                         LDB_ERR_OPERATIONS_ERROR);
3118         }
3119
3120         talloc_free(ares);
3121
3122         return ldb_module_done(ar->req, NULL, NULL, LDB_SUCCESS);
3123 }
3124
3125 static int replmd_replicated_uptodate_modify(struct replmd_replicated_request *ar)
3126 {
3127         struct ldb_context *ldb;
3128         struct ldb_request *change_req;
3129         enum ndr_err_code ndr_err;
3130         struct ldb_message *msg;
3131         struct replUpToDateVectorBlob ouv;
3132         const struct ldb_val *ouv_value;
3133         const struct drsuapi_DsReplicaCursor2CtrEx *ruv;
3134         struct replUpToDateVectorBlob nuv;
3135         struct ldb_val nuv_value;
3136         struct ldb_message_element *nuv_el = NULL;
3137         const struct GUID *our_invocation_id;
3138         struct ldb_message_element *orf_el = NULL;
3139         struct repsFromToBlob nrf;
3140         struct ldb_val *nrf_value = NULL;
3141         struct ldb_message_element *nrf_el = NULL;
3142         unsigned int i;
3143         uint32_t j,ni=0;
3144         bool found = false;
3145         time_t t = time(NULL);
3146         NTTIME now;
3147         int ret;
3148
3149         ldb = ldb_module_get_ctx(ar->module);
3150         ruv = ar->objs->uptodateness_vector;
3151         ZERO_STRUCT(ouv);
3152         ouv.version = 2;
3153         ZERO_STRUCT(nuv);
3154         nuv.version = 2;
3155
3156         unix_to_nt_time(&now, t);
3157
3158         /*
3159          * first create the new replUpToDateVector
3160          */
3161         ouv_value = ldb_msg_find_ldb_val(ar->search_msg, "replUpToDateVector");
3162         if (ouv_value) {
3163                 ndr_err = ndr_pull_struct_blob(ouv_value, ar,
3164                                                lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), &ouv,
3165                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3166                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3167                         NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
3168                         return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
3169                 }
3170
3171                 if (ouv.version != 2) {
3172                         return replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
3173                 }
3174         }
3175
3176         /*
3177          * the new uptodateness vector will at least
3178          * contain 1 entry, one for the source_dsa
3179          *
3180          * plus optional values from our old vector and the one from the source_dsa
3181          */
3182         nuv.ctr.ctr2.count = 1 + ouv.ctr.ctr2.count;
3183         if (ruv) nuv.ctr.ctr2.count += ruv->count;
3184         nuv.ctr.ctr2.cursors = talloc_array(ar,
3185                                             struct drsuapi_DsReplicaCursor2,
3186                                             nuv.ctr.ctr2.count);
3187         if (!nuv.ctr.ctr2.cursors) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3188
3189         /* first copy the old vector */
3190         for (i=0; i < ouv.ctr.ctr2.count; i++) {
3191                 nuv.ctr.ctr2.cursors[ni] = ouv.ctr.ctr2.cursors[i];
3192                 ni++;
3193         }
3194
3195         /* get our invocation_id if we have one already attached to the ldb */
3196         our_invocation_id = samdb_ntds_invocation_id(ldb);
3197
3198         /* merge in the source_dsa vector is available */
3199         for (i=0; (ruv && i < ruv->count); i++) {
3200                 found = false;
3201
3202                 if (our_invocation_id &&
3203                     GUID_equal(&ruv->cursors[i].source_dsa_invocation_id,
3204                                our_invocation_id)) {
3205                         continue;
3206                 }
3207
3208                 for (j=0; j < ni; j++) {
3209                         if (!GUID_equal(&ruv->cursors[i].source_dsa_invocation_id,
3210                                         &nuv.ctr.ctr2.cursors[j].source_dsa_invocation_id)) {
3211                                 continue;
3212                         }
3213
3214                         found = true;
3215
3216                         /*
3217                          * we update only the highest_usn and not the latest_sync_success time,
3218                          * because the last success stands for direct replication
3219                          */
3220                         if (ruv->cursors[i].highest_usn > nuv.ctr.ctr2.cursors[j].highest_usn) {
3221                                 nuv.ctr.ctr2.cursors[j].highest_usn = ruv->cursors[i].highest_usn;
3222                         }
3223                         break;                  
3224                 }
3225
3226                 if (found) continue;
3227
3228                 /* if it's not there yet, add it */
3229                 nuv.ctr.ctr2.cursors[ni] = ruv->cursors[i];
3230                 ni++;
3231         }
3232
3233         /*
3234          * merge in the current highwatermark for the source_dsa
3235          */
3236         found = false;
3237         for (j=0; j < ni; j++) {
3238                 if (!GUID_equal(&ar->objs->source_dsa->source_dsa_invocation_id,
3239                                 &nuv.ctr.ctr2.cursors[j].source_dsa_invocation_id)) {
3240                         continue;
3241                 }
3242
3243                 found = true;
3244
3245                 /*
3246                  * here we update the highest_usn and last_sync_success time
3247                  * because we're directly replicating from the source_dsa
3248                  *
3249                  * and use the tmp_highest_usn because this is what we have just applied
3250                  * to our ldb
3251                  */
3252                 nuv.ctr.ctr2.cursors[j].highest_usn             = ar->objs->source_dsa->highwatermark.tmp_highest_usn;
3253                 nuv.ctr.ctr2.cursors[j].last_sync_success       = now;
3254                 break;
3255         }
3256         if (!found) {
3257                 /*
3258                  * here we update the highest_usn and last_sync_success time
3259                  * because we're directly replicating from the source_dsa
3260                  *
3261                  * and use the tmp_highest_usn because this is what we have just applied
3262                  * to our ldb
3263                  */
3264                 nuv.ctr.ctr2.cursors[ni].source_dsa_invocation_id= ar->objs->source_dsa->source_dsa_invocation_id;
3265                 nuv.ctr.ctr2.cursors[ni].highest_usn            = ar->objs->source_dsa->highwatermark.tmp_highest_usn;
3266                 nuv.ctr.ctr2.cursors[ni].last_sync_success      = now;
3267                 ni++;
3268         }
3269
3270         /*
3271          * finally correct the size of the cursors array
3272          */
3273         nuv.ctr.ctr2.count = ni;
3274
3275         /*
3276          * sort the cursors
3277          */
3278         TYPESAFE_QSORT(nuv.ctr.ctr2.cursors, nuv.ctr.ctr2.count, drsuapi_DsReplicaCursor2_compare);
3279
3280         /*
3281          * create the change ldb_message
3282          */
3283         msg = ldb_msg_new(ar);
3284         if (!msg) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3285         msg->dn = ar->search_msg->dn;
3286
3287         ndr_err = ndr_push_struct_blob(&nuv_value, msg, 
3288                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), 
3289                                        &nuv,
3290                                        (ndr_push_flags_fn_t)ndr_push_replUpToDateVectorBlob);
3291         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3292                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
3293                 return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
3294         }
3295         ret = ldb_msg_add_value(msg, "replUpToDateVector", &nuv_value, &nuv_el);
3296         if (ret != LDB_SUCCESS) {
3297                 return replmd_replicated_request_error(ar, ret);
3298         }
3299         nuv_el->flags = LDB_FLAG_MOD_REPLACE;
3300
3301         /*
3302          * now create the new repsFrom value from the given repsFromTo1 structure
3303          */
3304         ZERO_STRUCT(nrf);
3305         nrf.version                                     = 1;
3306         nrf.ctr.ctr1                                    = *ar->objs->source_dsa;
3307         /* and fix some values... */
3308         nrf.ctr.ctr1.consecutive_sync_failures          = 0;
3309         nrf.ctr.ctr1.last_success                       = now;
3310         nrf.ctr.ctr1.last_attempt                       = now;
3311         nrf.ctr.ctr1.result_last_attempt                = WERR_OK;
3312         nrf.ctr.ctr1.highwatermark.highest_usn          = nrf.ctr.ctr1.highwatermark.tmp_highest_usn;
3313
3314         /*
3315          * first see if we already have a repsFrom value for the current source dsa
3316          * if so we'll later replace this value
3317          */
3318         orf_el = ldb_msg_find_element(ar->search_msg, "repsFrom");
3319         if (orf_el) {
3320                 for (i=0; i < orf_el->num_values; i++) {
3321                         struct repsFromToBlob *trf;
3322
3323                         trf = talloc(ar, struct repsFromToBlob);
3324                         if (!trf) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3325
3326                         ndr_err = ndr_pull_struct_blob(&orf_el->values[i], trf, lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")), trf,
3327                                                        (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
3328                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3329                                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
3330                                 return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
3331                         }
3332
3333                         if (trf->version != 1) {
3334                                 return replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
3335                         }
3336
3337                         /*
3338                          * we compare the source dsa objectGUID not the invocation_id
3339                          * because we want only one repsFrom value per source dsa
3340                          * and when the invocation_id of the source dsa has changed we don't need 
3341                          * the old repsFrom with the old invocation_id
3342                          */
3343                         if (!GUID_equal(&trf->ctr.ctr1.source_dsa_obj_guid,
3344                                         &ar->objs->source_dsa->source_dsa_obj_guid)) {
3345                                 talloc_free(trf);
3346                                 continue;
3347                         }
3348
3349                         talloc_free(trf);
3350                         nrf_value = &orf_el->values[i];
3351                         break;
3352                 }
3353
3354                 /*
3355                  * copy over all old values to the new ldb_message
3356                  */
3357                 ret = ldb_msg_add_empty(msg, "repsFrom", 0, &nrf_el);
3358                 if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
3359                 *nrf_el = *orf_el;
3360         }
3361
3362         /*
3363          * if we haven't found an old repsFrom value for the current source dsa
3364          * we'll add a new value
3365          */
3366         if (!nrf_value) {
3367                 struct ldb_val zero_value;
3368                 ZERO_STRUCT(zero_value);
3369                 ret = ldb_msg_add_value(msg, "repsFrom", &zero_value, &nrf_el);
3370                 if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
3371
3372                 nrf_value = &nrf_el->values[nrf_el->num_values - 1];
3373         }
3374
3375         /* we now fill the value which is already attached to ldb_message */
3376         ndr_err = ndr_push_struct_blob(nrf_value, msg, 
3377                                        lp_iconv_convenience(ldb_get_opaque(ldb, "loadparm")),
3378                                        &nrf,
3379                                        (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
3380         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3381                 NTSTATUS nt_status = ndr_map_error2ntstatus(ndr_err);
3382                 return replmd_replicated_request_werror(ar, ntstatus_to_werror(nt_status));
3383         }
3384
3385         /* 
3386          * the ldb_message_element for the attribute, has all the old values and the new one
3387          * so we'll replace the whole attribute with all values
3388          */
3389         nrf_el->flags = LDB_FLAG_MOD_REPLACE;
3390
3391         if (DEBUGLVL(4)) {
3392                 char *s = ldb_ldif_message_string(ldb, ar, LDB_CHANGETYPE_MODIFY, msg);
3393                 DEBUG(4, ("DRS replication uptodate modify message:\n%s\n", s));
3394                 talloc_free(s);
3395         }
3396
3397         /* prepare the ldb_modify() request */
3398         ret = ldb_build_mod_req(&change_req,
3399                                 ldb,
3400                                 ar,
3401                                 msg,
3402                                 ar->controls,
3403                                 ar,
3404                                 replmd_replicated_uptodate_modify_callback,
3405                                 ar->req);
3406         if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
3407
3408         return ldb_next_request(ar->module, change_req);
3409 }
3410
3411 static int replmd_replicated_uptodate_search_callback(struct ldb_request *req,
3412                                                       struct ldb_reply *ares)
3413 {
3414         struct replmd_replicated_request *ar = talloc_get_type(req->context,
3415                                                struct replmd_replicated_request);
3416         int ret;
3417
3418         if (!ares) {
3419                 return ldb_module_done(ar->req, NULL, NULL,
3420                                         LDB_ERR_OPERATIONS_ERROR);
3421         }
3422         if (ares->error != LDB_SUCCESS &&
3423             ares->error != LDB_ERR_NO_SUCH_OBJECT) {
3424                 return ldb_module_done(ar->req, ares->controls,
3425                                         ares->response, ares->error);
3426         }
3427
3428         switch (ares->type) {
3429         case LDB_REPLY_ENTRY:
3430                 ar->search_msg = talloc_steal(ar, ares->message);
3431                 break;
3432
3433         case LDB_REPLY_REFERRAL:
3434                 /* we ignore referrals */
3435                 break;
3436
3437         case LDB_REPLY_DONE:
3438                 if (ar->search_msg == NULL) {
3439                         ret = replmd_replicated_request_werror(ar, WERR_DS_DRA_INTERNAL_ERROR);
3440                 } else {
3441                         ret = replmd_replicated_uptodate_modify(ar);
3442                 }
3443                 if (ret != LDB_SUCCESS) {
3444                         return ldb_module_done(ar->req, NULL, NULL, ret);
3445                 }
3446         }
3447
3448         talloc_free(ares);
3449         return LDB_SUCCESS;
3450 }
3451
3452
3453 static int replmd_replicated_uptodate_vector(struct replmd_replicated_request *ar)
3454 {
3455         struct ldb_context *ldb;
3456         int ret;
3457         static const char *attrs[] = {
3458                 "replUpToDateVector",
3459                 "repsFrom",
3460                 NULL
3461         };
3462         struct ldb_request *search_req;
3463
3464         ldb = ldb_module_get_ctx(ar->module);
3465         ar->search_msg = NULL;
3466
3467         ret = ldb_build_search_req(&search_req,
3468                                    ldb,
3469                                    ar,
3470                                    ar->objs->partition_dn,
3471                                    LDB_SCOPE_BASE,
3472                                    "(objectClass=*)",
3473                                    attrs,
3474                                    NULL,
3475                                    ar,
3476                                    replmd_replicated_uptodate_search_callback,
3477                                    ar->req);
3478         if (ret != LDB_SUCCESS) return replmd_replicated_request_error(ar, ret);
3479
3480         return ldb_next_request(ar->module, search_req);
3481 }
3482
3483
3484
3485 static int replmd_extended_replicated_objects(struct ldb_module *module, struct ldb_request *req)
3486 {
3487         struct ldb_context *ldb;
3488         struct dsdb_extended_replicated_objects *objs;
3489         struct replmd_replicated_request *ar;
3490         struct ldb_control **ctrls;
3491         int ret;
3492         uint32_t i;
3493         struct replmd_private *replmd_private = 
3494                 talloc_get_type(ldb_module_get_private(module), struct replmd_private);
3495
3496         ldb = ldb_module_get_ctx(module);
3497
3498         ldb_debug(ldb, LDB_DEBUG_TRACE, "replmd_extended_replicated_objects\n");
3499
3500         objs = talloc_get_type(req->op.extended.data, struct dsdb_extended_replicated_objects);
3501         if (!objs) {
3502                 ldb_debug(ldb, LDB_DEBUG_FATAL, "replmd_extended_replicated_objects: invalid extended data\n");
3503                 return LDB_ERR_PROTOCOL_ERROR;
3504         }
3505
3506         if (objs->version != DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION) {
3507                 ldb_debug(ldb, LDB_DEBUG_FATAL, "replmd_extended_replicated_objects: extended data invalid version [%u != %u]\n",
3508                           objs->version, DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION);
3509                 return LDB_ERR_PROTOCOL_ERROR;
3510         }
3511
3512         ar = replmd_ctx_init(module, req);
3513         if (!ar)
3514                 return LDB_ERR_OPERATIONS_ERROR;
3515
3516         /* Set the flags to have the replmd_op_callback run over the full set of objects */
3517         ar->apply_mode = true;
3518         ar->objs = objs;
3519         ar->schema = dsdb_get_schema(ldb, ar);
3520         if (!ar->schema) {
3521                 ldb_debug_set(ldb, LDB_DEBUG_FATAL, "replmd_ctx_init: no loaded schema found\n");
3522                 talloc_free(ar);
3523                 DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
3524                 return LDB_ERR_CONSTRAINT_VIOLATION;
3525         }
3526
3527         ctrls = req->controls;
3528
3529         if (req->controls) {
3530                 req->controls = talloc_memdup(ar, req->controls,
3531                                               talloc_get_size(req->controls));
3532                 if (!req->controls) return replmd_replicated_request_werror(ar, WERR_NOMEM);
3533         }
3534
3535         ret = ldb_request_add_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID, false, NULL);
3536         if (ret != LDB_SUCCESS) {
3537                 return ret;
3538         }
3539
3540         ar->controls = req->controls;
3541         req->controls = ctrls;
3542
3543         DEBUG(4,("linked_attributes_count=%u\n", objs->linked_attributes_count));
3544
3545         /* save away the linked attributes for the end of the
3546            transaction */
3547         for (i=0; i<ar->objs->linked_attributes_count; i++) {
3548                 struct la_entry *la_entry;
3549
3550                 if (replmd_private->la_ctx == NULL) {
3551                         replmd_private->la_ctx = talloc_new(replmd_private);
3552                 }
3553                 la_entry = talloc(replmd_private->la_ctx, struct la_entry);
3554                 if (la_entry == NULL) {
3555                         ldb_oom(ldb);
3556                         return LDB_ERR_OPERATIONS_ERROR;
3557                 }
3558                 la_entry->la = talloc(la_entry, struct drsuapi_DsReplicaLinkedAttribute);
3559                 if (la_entry->la == NULL) {
3560                         talloc_free(la_entry);
3561                         ldb_oom(ldb);
3562                         return LDB_ERR_OPERATIONS_ERROR;
3563                 }
3564                 *la_entry->la = ar->objs->linked_attributes[i];
3565
3566                 /* we need to steal the non-scalars so they stay
3567                    around until the end of the transaction */
3568                 talloc_steal(la_entry->la, la_entry->la->identifier);
3569                 talloc_steal(la_entry->la, la_entry->la->value.blob);
3570
3571                 DLIST_ADD(replmd_private->la_list, la_entry);
3572         }
3573
3574         return replmd_replicated_apply_next(ar);
3575 }
3576
3577 /*
3578   process one linked attribute structure
3579  */
3580 static int replmd_process_linked_attribute(struct ldb_module *module,
3581                                            struct la_entry *la_entry)
3582 {                                          
3583         struct drsuapi_DsReplicaLinkedAttribute *la = la_entry->la;
3584         struct ldb_context *ldb = ldb_module_get_ctx(module);
3585         struct ldb_message *msg;
3586         TALLOC_CTX *tmp_ctx = talloc_new(la_entry);
3587         const struct dsdb_schema *schema = dsdb_get_schema(ldb, tmp_ctx);
3588         int ret;
3589         const struct dsdb_attribute *attr;
3590         struct dsdb_dn *dsdb_dn;
3591         uint64_t seq_num = 0;
3592         struct ldb_message_element *old_el;
3593         WERROR status;
3594         time_t t = time(NULL);
3595         struct ldb_result *res;
3596         const char *attrs[2];
3597         struct parsed_dn *pdn_list, *pdn;
3598         struct GUID guid = GUID_zero();
3599         NTSTATUS ntstatus;
3600         bool active = (la->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)?true:false;
3601         const struct GUID *our_invocation_id;
3602
3603 /*
3604 linked_attributes[0]:                                                     
3605      &objs->linked_attributes[i]: struct drsuapi_DsReplicaLinkedAttribute 
3606         identifier               : *                                      
3607             identifier: struct drsuapi_DsReplicaObjectIdentifier          
3608                 __ndr_size               : 0x0000003a (58)                
3609                 __ndr_size_sid           : 0x00000000 (0)                 
3610                 guid                     : 8e95b6a9-13dd-4158-89db-3220a5be5cc7
3611                 sid                      : S-0-0                               
3612                 __ndr_size_dn            : 0x00000000 (0)                      
3613                 dn                       : ''                                  
3614         attid                    : DRSUAPI_ATTRIBUTE_member (0x1F)             
3615         value: struct drsuapi_DsAttributeValue                                 
3616             __ndr_size               : 0x0000007e (126)                        
3617             blob                     : *                                       
3618                 blob                     : DATA_BLOB length=126                
3619         flags                    : 0x00000001 (1)                              
3620                1: DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE                      
3621         originating_add_time     : Wed Sep  2 22:20:01 2009 EST                
3622         meta_data: struct drsuapi_DsReplicaMetaData                            
3623             version                  : 0x00000015 (21)                         
3624             originating_change_time  : Wed Sep  2 23:39:07 2009 EST            
3625             originating_invocation_id: 794640f3-18cf-40ee-a211-a93992b67a64    
3626             originating_usn          : 0x000000000001e19c (123292)             
3627
3628 (for cases where the link is to a normal DN)
3629      &target: struct drsuapi_DsReplicaObjectIdentifier3                        
3630         __ndr_size               : 0x0000007e (126)                            
3631         __ndr_size_sid           : 0x0000001c (28)                             
3632         guid                     : 7639e594-db75-4086-b0d4-67890ae46031        
3633         sid                      : S-1-5-21-2848215498-2472035911-1947525656-19924
3634         __ndr_size_dn            : 0x00000022 (34)                                
3635         dn                       : 'CN=UOne,OU=TestOU,DC=vsofs8,DC=com'           
3636  */
3637         
3638         /* find the attribute being modified */
3639         attr = dsdb_attribute_by_attributeID_id(schema, la->attid);
3640         if (attr == NULL) {
3641                 DEBUG(0, (__location__ ": Unable to find attributeID 0x%x\n", la->attid));
3642                 talloc_free(tmp_ctx);
3643                 return LDB_ERR_OPERATIONS_ERROR;
3644         }
3645
3646         attrs[0] = attr->lDAPDisplayName;
3647         attrs[1] = NULL;
3648
3649         /* get the existing message from the db for the object with
3650            this GUID, returning attribute being modified. We will then
3651            use this msg as the basis for a modify call */
3652         ret = dsdb_module_search(module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
3653                                  DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
3654                                  DSDB_SEARCH_SHOW_DELETED |
3655                                  DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT |
3656                                  DSDB_SEARCH_REVEAL_INTERNALS,
3657                                  "objectGUID=%s", GUID_string(tmp_ctx, &la->identifier->guid));
3658         if (ret != LDB_SUCCESS) {
3659                 talloc_free(tmp_ctx);
3660                 return ret;
3661         }
3662         if (res->count != 1) {
3663                 ldb_asprintf_errstring(ldb, "DRS linked attribute for GUID %s - DN not found",
3664                                        GUID_string(tmp_ctx, &la->identifier->guid));
3665                 talloc_free(tmp_ctx);
3666                 return LDB_ERR_NO_SUCH_OBJECT;
3667         }
3668         msg = res->msgs[0];
3669
3670         if (msg->num_elements == 0) {
3671                 ret = ldb_msg_add_empty(msg, attr->lDAPDisplayName, LDB_FLAG_MOD_REPLACE, &old_el);
3672                 if (ret != LDB_SUCCESS) {
3673                         ldb_module_oom(module);
3674                         talloc_free(tmp_ctx);
3675                         return LDB_ERR_OPERATIONS_ERROR;
3676                 }
3677         } else {
3678                 old_el = &msg->elements[0];
3679                 old_el->flags = LDB_FLAG_MOD_REPLACE;
3680         }
3681
3682         /* parse the existing links */
3683         ret = get_parsed_dns(module, tmp_ctx, old_el, &pdn_list, attr->syntax->ldap_oid);
3684         if (ret != LDB_SUCCESS) {
3685                 talloc_free(tmp_ctx);
3686                 return ret;
3687         }
3688
3689         /* get our invocationId */
3690         our_invocation_id = samdb_ntds_invocation_id(ldb);
3691         if (!our_invocation_id) {
3692                 ldb_debug_set(ldb, LDB_DEBUG_ERROR, __location__ ": unable to find invocationId\n");
3693                 talloc_free(tmp_ctx);
3694                 return LDB_ERR_OPERATIONS_ERROR;
3695         }
3696
3697         ret = replmd_check_upgrade_links(pdn_list, old_el->num_values, our_invocation_id);
3698         if (ret != LDB_SUCCESS) {
3699                 talloc_free(tmp_ctx);
3700                 return ret;
3701         }
3702
3703         status = dsdb_dn_la_from_blob(ldb, attr, schema, tmp_ctx, la->value.blob, &dsdb_dn);
3704         if (!W_ERROR_IS_OK(status)) {
3705                 ldb_asprintf_errstring(ldb, "Failed to parsed linked attribute blob for %s on %s - %s\n",
3706                                        old_el->name, ldb_dn_get_linearized(msg->dn), win_errstr(status));
3707                 return LDB_ERR_OPERATIONS_ERROR;
3708         }
3709
3710         ntstatus = dsdb_get_extended_dn_guid(dsdb_dn->dn, &guid, "GUID");
3711         if (!NT_STATUS_IS_OK(ntstatus) && active) {
3712                 ldb_asprintf_errstring(ldb, "Failed to find GUID in linked attribute blob for %s on %s from %s",
3713                                        old_el->name,
3714                                        ldb_dn_get_linearized(dsdb_dn->dn),
3715                                        ldb_dn_get_linearized(msg->dn));
3716                 return LDB_ERR_OPERATIONS_ERROR;
3717         }
3718
3719         /* re-resolve the DN by GUID, as the DRS server may give us an
3720            old DN value */
3721         ret = dsdb_module_dn_by_guid(module, dsdb_dn, &guid, &dsdb_dn->dn);
3722         if (ret != LDB_SUCCESS) {
3723                 ldb_asprintf_errstring(ldb, __location__ ": Failed to re-resolve GUID %s",
3724                                        GUID_string(tmp_ctx, &guid));
3725                 talloc_free(tmp_ctx);
3726                 return ret;
3727         }
3728
3729         /* see if this link already exists */
3730         pdn = parsed_dn_find(pdn_list, old_el->num_values, &guid, dsdb_dn->dn);
3731         if (pdn != NULL) {
3732                 /* see if this update is newer than what we have already */
3733                 struct GUID invocation_id = GUID_zero();
3734                 uint32_t version = 0;
3735                 NTTIME change_time = 0;
3736                 uint32_t rmd_flags = dsdb_dn_rmd_flags(pdn->dsdb_dn->dn);
3737
3738                 dsdb_get_extended_dn_guid(pdn->dsdb_dn->dn, &invocation_id, "RMD_INVOCID");
3739                 dsdb_get_extended_dn_uint32(pdn->dsdb_dn->dn, &version, "RMD_VERSION");
3740                 dsdb_get_extended_dn_nttime(pdn->dsdb_dn->dn, &change_time, "RMD_CHANGETIME");
3741
3742                 if (!replmd_update_is_newer(&invocation_id,
3743                                             &la->meta_data.originating_invocation_id,
3744                                             version,
3745                                             la->meta_data.version,
3746                                             change_time,
3747                                             la->meta_data.originating_change_time)) {
3748                         DEBUG(1,("Discarding older DRS linked attribute update to %s on %s from %s\n",
3749                                  old_el->name, ldb_dn_get_linearized(msg->dn),
3750                                  GUID_string(tmp_ctx, &la->meta_data.originating_invocation_id)));
3751                         talloc_free(tmp_ctx);
3752                         return LDB_SUCCESS;
3753                 }
3754
3755                 /* get a seq_num for this change */
3756                 ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &seq_num);
3757                 if (ret != LDB_SUCCESS) {
3758                         talloc_free(tmp_ctx);
3759                         return ret;
3760                 }
3761
3762                 if (!(rmd_flags & DSDB_RMD_FLAG_DELETED)) {
3763                         /* remove the existing backlink */
3764                         ret = replmd_add_backlink(module, schema, &la->identifier->guid, &guid, false, attr, false);
3765                         if (ret != LDB_SUCCESS) {
3766                                 talloc_free(tmp_ctx);
3767                                 return ret;
3768                         }
3769                 }
3770
3771                 ret = replmd_update_la_val(tmp_ctx, pdn->v, dsdb_dn, pdn->dsdb_dn,
3772                                            &la->meta_data.originating_invocation_id,
3773                                            la->meta_data.originating_usn, seq_num,
3774                                            la->meta_data.originating_change_time,
3775                                            la->meta_data.version,
3776                                            !active);
3777                 if (ret != LDB_SUCCESS) {
3778                         talloc_free(tmp_ctx);
3779                         return ret;
3780                 }
3781
3782                 if (active) {
3783                         /* add the new backlink */
3784                         ret = replmd_add_backlink(module, schema, &la->identifier->guid, &guid, true, attr, false);
3785                         if (ret != LDB_SUCCESS) {
3786                                 talloc_free(tmp_ctx);
3787                                 return ret;
3788                         }
3789                 }
3790         } else {
3791                 /* get a seq_num for this change */
3792                 ret = ldb_sequence_number(ldb, LDB_SEQ_NEXT, &seq_num);
3793                 if (ret != LDB_SUCCESS) {
3794                         talloc_free(tmp_ctx);
3795                         return ret;
3796                 }
3797
3798                 old_el->values = talloc_realloc(msg->elements, old_el->values,
3799                                                 struct ldb_val, old_el->num_values+1);
3800                 if (!old_el->values) {
3801                         ldb_module_oom(module);
3802                         return LDB_ERR_OPERATIONS_ERROR;
3803                 }
3804                 old_el->num_values++;
3805
3806                 ret = replmd_build_la_val(tmp_ctx, &old_el->values[old_el->num_values-1], dsdb_dn,
3807                                           &la->meta_data.originating_invocation_id,
3808                                           la->meta_data.originating_usn, seq_num,
3809                                           la->meta_data.originating_change_time,
3810                                           la->meta_data.version,
3811                                           (la->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)?false:true);
3812                 if (ret != LDB_SUCCESS) {
3813                         talloc_free(tmp_ctx);
3814                         return ret;
3815                 }
3816
3817                 if (active) {
3818                         ret = replmd_add_backlink(module, schema, &la->identifier->guid, &guid,
3819                                                   true, attr, false);
3820                         if (ret != LDB_SUCCESS) {
3821                                 talloc_free(tmp_ctx);
3822                                 return ret;
3823                         }
3824                 }
3825         }
3826
3827         /* we only change whenChanged and uSNChanged if the seq_num
3828            has changed */
3829         if (add_time_element(msg, "whenChanged", t) != LDB_SUCCESS) {
3830                 talloc_free(tmp_ctx);
3831                 return LDB_ERR_OPERATIONS_ERROR;
3832         }
3833
3834         if (add_uint64_element(msg, "uSNChanged", seq_num) != LDB_SUCCESS) {
3835                 talloc_free(tmp_ctx);
3836                 return LDB_ERR_OPERATIONS_ERROR;
3837         }
3838
3839         ret = dsdb_check_single_valued_link(attr, old_el);
3840         if (ret != LDB_SUCCESS) {
3841                 talloc_free(tmp_ctx);
3842                 return ret;
3843         }
3844
3845         ret = dsdb_module_modify(module, msg, DSDB_MODIFY_RELAX);
3846         if (ret != LDB_SUCCESS) {
3847                 ldb_debug(ldb, LDB_DEBUG_WARNING, "Failed to apply linked attribute change '%s'\n%s\n",
3848                           ldb_errstring(ldb),
3849                           ldb_ldif_message_string(ldb, tmp_ctx, LDB_CHANGETYPE_MODIFY, msg));
3850                 talloc_free(tmp_ctx);
3851                 return ret;
3852         }
3853         
3854         talloc_free(tmp_ctx);
3855
3856         return ret;     
3857 }
3858
3859 static int replmd_extended(struct ldb_module *module, struct ldb_request *req)
3860 {
3861         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_REPLICATED_OBJECTS_OID) == 0) {
3862                 return replmd_extended_replicated_objects(module, req);
3863         }
3864
3865         return ldb_next_request(module, req);
3866 }
3867
3868
3869 /*
3870   we hook into the transaction operations to allow us to 
3871   perform the linked attribute updates at the end of the whole
3872   transaction. This allows a forward linked attribute to be created
3873   before the object is created. During a vampire, w2k8 sends us linked
3874   attributes before the objects they are part of.
3875  */
3876 static int replmd_start_transaction(struct ldb_module *module)
3877 {
3878         /* create our private structure for this transaction */
3879         struct replmd_private *replmd_private = talloc_get_type(ldb_module_get_private(module),
3880                                                                 struct replmd_private);
3881         replmd_txn_cleanup(replmd_private);
3882
3883         /* free any leftover mod_usn records from cancelled
3884            transactions */
3885         while (replmd_private->ncs) {
3886                 struct nc_entry *e = replmd_private->ncs;
3887                 DLIST_REMOVE(replmd_private->ncs, e);
3888                 talloc_free(e);
3889         }
3890
3891         return ldb_next_start_trans(module);
3892 }
3893
3894 /*
3895   on prepare commit we loop over our queued la_context structures and
3896   apply each of them  
3897  */
3898 static int replmd_prepare_commit(struct ldb_module *module)
3899 {
3900         struct replmd_private *replmd_private = 
3901                 talloc_get_type(ldb_module_get_private(module), struct replmd_private);
3902         struct la_entry *la, *prev;
3903         struct la_backlink *bl;
3904         int ret;
3905
3906         /* walk the list backwards, to do the first entry first, as we
3907          * added the entries with DLIST_ADD() which puts them at the
3908          * start of the list */
3909         for (la = DLIST_TAIL(replmd_private->la_list); la; la=prev) {
3910                 prev = DLIST_PREV(la);
3911                 DLIST_REMOVE(replmd_private->la_list, la);
3912                 ret = replmd_process_linked_attribute(module, la);
3913                 if (ret != LDB_SUCCESS) {
3914                         replmd_txn_cleanup(replmd_private);
3915                         return ret;
3916                 }
3917         }
3918
3919         /* process our backlink list, creating and deleting backlinks
3920            as necessary */
3921         for (bl=replmd_private->la_backlinks; bl; bl=bl->next) {
3922                 ret = replmd_process_backlink(module, bl);
3923                 if (ret != LDB_SUCCESS) {
3924                         replmd_txn_cleanup(replmd_private);
3925                         return ret;
3926                 }
3927         }
3928
3929         replmd_txn_cleanup(replmd_private);
3930
3931         /* possibly change @REPLCHANGED */
3932         ret = replmd_notify_store(module);
3933         if (ret != LDB_SUCCESS) {
3934                 return ret;
3935         }
3936         
3937         return ldb_next_prepare_commit(module);
3938 }
3939
3940 static int replmd_del_transaction(struct ldb_module *module)
3941 {
3942         struct replmd_private *replmd_private = 
3943                 talloc_get_type(ldb_module_get_private(module), struct replmd_private);
3944         replmd_txn_cleanup(replmd_private);
3945
3946         return ldb_next_del_trans(module);
3947 }
3948
3949
3950 _PUBLIC_ const struct ldb_module_ops ldb_repl_meta_data_module_ops = {
3951         .name          = "repl_meta_data",
3952         .init_context      = replmd_init,
3953         .add               = replmd_add,
3954         .modify            = replmd_modify,
3955         .rename            = replmd_rename,
3956         .del               = replmd_delete,
3957         .extended          = replmd_extended,
3958         .start_transaction = replmd_start_transaction,
3959         .prepare_commit    = replmd_prepare_commit,
3960         .del_transaction   = replmd_del_transaction,
3961 };