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