s4:dsdb Don't segfault with ldb_transaction_prepare_commit() without begin()
[ira/wip.git] / source4 / dsdb / samdb / ldb_modules / linked_attributes.c
index b3fdffe5669f6c88cb02eb8f408bba2958ed947d..bd9af5545e3c8533034cae97d5d5205d82bd417e 100644 (file)
@@ -2,6 +2,7 @@
    ldb database library
 
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2007
+   Copyright (C) Simo Sorce <idra@samba.org> 2008
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
  */
 
 #include "includes.h"
-#include "ldb/include/ldb.h"
-#include "ldb/include/ldb_errors.h"
-#include "ldb/include/ldb_private.h"
+#include "ldb_module.h"
+#include "dlinklist.h"
 #include "dsdb/samdb/samdb.h"
+#include "librpc/gen_ndr/ndr_misc.h"
 
-struct linked_attributes_context {
-       enum la_step {LA_SEARCH, LA_DO_OPS, LA_DO_ORIG} step;
-       struct ldb_module *module;
-       struct ldb_handle *handle;
-       struct ldb_request *orig_req;
-
-       struct ldb_request *search_req;
-       struct ldb_request **down_req;
-       struct ldb_request *orig_down_req;
-
-       int num_requests;
-       int finished_requests;
+struct la_private {
+       struct la_context *la_list;
+};
 
-       const char **linked_attrs;
+struct la_op_store {
+       struct la_op_store *next;
+       struct la_op_store *prev;
+       enum la_op {LA_OP_ADD, LA_OP_DEL} op;
+       struct GUID guid;
+       char *name;
+       char *value;
 };
 
 struct replace_context {
-       struct linked_attributes_context *ac;
+       struct la_context *ac;
+       unsigned int num_elements;
        struct ldb_message_element *el;
 };
 
-static int linked_attributes_rename_del_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares);
+struct la_context {
+       struct la_context *next, *prev;
+       const struct dsdb_schema *schema;
+       struct ldb_module *module;
+       struct ldb_request *req;
+       struct ldb_dn *partition_dn;
+       struct ldb_dn *add_dn;
+       struct ldb_dn *del_dn;
+       struct replace_context *rc;
+       struct la_op_store *ops;
+       struct ldb_extended *op_response;
+       struct ldb_control **op_controls;
+};
 
-static struct linked_attributes_context *linked_attributes_init_handle(struct ldb_request *req, 
-                                                                struct ldb_module *module)
+static struct la_context *linked_attributes_init(struct ldb_module *module,
+                                                struct ldb_request *req)
 {
-       struct linked_attributes_context *ac;
-       struct ldb_handle *h;
-
-       h = talloc_zero(req, struct ldb_handle);
-       if (h == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               return NULL;
-       }
+       struct ldb_context *ldb;
+       struct la_context *ac;
+       const struct ldb_control *partition_ctrl;
 
-       h->module = module;
+       ldb = ldb_module_get_ctx(module);
 
-       ac = talloc_zero(h, struct linked_attributes_context);
+       ac = talloc_zero(req, struct la_context);
        if (ac == NULL) {
-               ldb_set_errstring(module->ldb, "Out of Memory");
-               talloc_free(h);
+               ldb_oom(ldb);
                return NULL;
        }
 
-       h->private_data = ac;
-
+       ac->schema = dsdb_get_schema(ldb);
        ac->module = module;
-       ac->handle = h;
-       ac->orig_req = req;
+       ac->req = req;
+
+       /* remember the partition DN that came in, if given */
+       partition_ctrl = ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID);
+       if (partition_ctrl) {
+               const struct dsdb_control_current_partition *partition;
+               partition = talloc_get_type(partition_ctrl->data,
+                                           struct dsdb_control_current_partition);
+               SMB_ASSERT(partition && partition->version == DSDB_CONTROL_CURRENT_PARTITION_VERSION);
        
-       ac->orig_down_req = talloc(ac, struct ldb_request);
-       if (!ac->orig_down_req) {
-               ldb_oom(ac->module->ldb);
-               return NULL;
+               ac->partition_dn = ldb_dn_copy(ac, partition->dn);
        }
 
-       *ac->orig_down_req = *req;
+       return ac;
+}
 
-       req->handle = h;
+/*
+  turn a DN into a GUID
+ */
+static int la_guid_from_dn(struct la_context *ac, struct ldb_dn *dn, struct GUID *guid)
+{
+       const struct ldb_val *guid_val;
+       int ret;
 
-       return ac;
+       guid_val = ldb_dn_get_extended_component(dn, "GUID");
+       if (guid_val) {
+               /* there is a GUID embedded in the DN */
+               enum ndr_err_code ndr_err;
+               ndr_err = ndr_pull_struct_blob(guid_val, ac, NULL, guid,
+                                              (ndr_pull_flags_fn_t)ndr_pull_GUID);
+               if (ndr_err != NDR_ERR_SUCCESS) {
+                       DEBUG(0,(__location__ ": Failed to parse GUID\n"));
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+       } else {
+               ret = dsdb_find_guid_by_dn(ldb_module_get_ctx(ac->module), dn, guid);
+               if (ret != LDB_SUCCESS) {
+                       DEBUG(4,(__location__ ": Failed to find GUID for dn %s\n",
+                                ldb_dn_get_linearized(dn)));
+                       return ret;
+               }
+       }
+       return LDB_SUCCESS;
 }
 
+
 /* Common routine to handle reading the attributes and creating a
  * series of modify requests */
-
-static int setup_modifies(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
-                         struct linked_attributes_context *ac,
-                         const struct ldb_message *msg, 
-                         struct ldb_dn *olddn, struct ldb_dn *newdn) 
+static int la_store_op(struct la_context *ac,
+                      enum la_op op, struct ldb_val *dn,
+                      const char *name)
 {
-       int i, j, ret = LDB_SUCCESS;
-       const struct dsdb_schema *schema = dsdb_get_schema(ldb);
-       /* Look up each of the returned attributes */
-       /* Find their schema */
-       /* And it is an actual entry: now create a series of modify requests */
-       for (i=0; i < msg->num_elements; i++) {
-               int otherid;
-               const struct dsdb_attribute *target_attr;
-               const struct ldb_message_element *el = &msg->elements[i];
-               const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
-               if (!schema_attr) {
-                       ldb_asprintf_errstring(ldb, 
-                                              "attribute %s is not a valid attribute in schema", el->name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
-               }
-               /* We have a valid attribute, but if it's not linked they maybe we just got an extra return on our search... */
-               if (schema_attr->linkID == 0) {
-                       continue;
-               }
-               
-               /* Depending on which direction this link is in, we need to find it's partner */
-               if ((schema_attr->linkID & 1) == 1) {
-                       otherid = schema_attr->linkID - 1;
-               } else {
-                       otherid = schema_attr->linkID + 1;
-               }
-               
-               /* Now find the target attribute */
-               target_attr = dsdb_attribute_by_linkID(schema, otherid);
-               if (!target_attr) {
-                       ldb_asprintf_errstring(ldb, 
-                                              "attribute %s does not have valid link target", el->name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
-               }
-               
-               /* For each value being moded, we need to setup the modify */
-               for (j=0; j < el->num_values; j++) {
-                       struct ldb_message_element *ret_el;
-                       struct ldb_request *new_req;
-                       struct ldb_message *new_msg;
-
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+       struct ldb_context *ldb;
+       struct la_op_store *os;
+       struct ldb_dn *op_dn;
+       int ret;
 
-                       /* Create the modify request */
-                       new_msg = ldb_msg_new(ac->down_req);
-                       if (!new_msg) {
-                               ldb_oom(ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       new_msg->dn = ldb_dn_new(new_msg, ldb, (char *)el->values[j].data);
-                       if (!new_msg->dn) {
-                               ldb_asprintf_errstring(ldb, 
-                                                      "attribute %s value %s was not a valid DN", msg->elements[i].name,
-                                                      el->values[j].data);
-                               return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
-                       }
-                       
-                       if (olddn) {
-                               ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                                       LDB_FLAG_MOD_DELETE, &ret_el);
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
-                               }       
-                               ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
-                               if (!ret_el->values) {
-                                       ldb_oom(ldb);
-                                       return LDB_ERR_OPERATIONS_ERROR;
-                               }
-                               ret_el->values[0] = data_blob_string_const(ldb_dn_get_linearized(olddn));
-                               ret_el->num_values = 1;
-                       }
-                       
-                       if (newdn) {
-                               ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                                       LDB_FLAG_MOD_ADD, &ret_el);
-                               if (ret != LDB_SUCCESS) {
-                                       return ret;
-                               }       
-                               ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
-                               if (!ret_el->values) {
-                                       ldb_oom(ldb);
-                                       return LDB_ERR_OPERATIONS_ERROR;
-                               }
-                               ret_el->values[0] = data_blob_string_const(ldb_dn_get_linearized(newdn));
-                               ret_el->num_values = 1;
-                       }
+       ldb = ldb_module_get_ctx(ac->module);
 
-                       ret = ldb_build_mod_req(&new_req, ldb, ac->down_req,
-                                               new_msg,
-                                               NULL,
-                                               NULL,
-                                               NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, new_msg);
-                       
-                       ldb_set_timeout_from_prev_req(ldb, ac->orig_req, new_req);
-                       
-                       ac->down_req[ac->num_requests] = new_req;
-                       ac->num_requests++;
-                       
+       op_dn = ldb_dn_from_ldb_val(ac, ldb, dn);
+       if (!op_dn) {
+               ldb_asprintf_errstring(ldb, 
+                                      "could not parse attribute as a DN");
+               return LDB_ERR_INVALID_DN_SYNTAX;
+       }
 
-                       /* Run the new request */
-                       ret = ldb_next_request(ac->module, new_req);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-               }
+       os = talloc_zero(ac, struct la_op_store);
+       if (!os) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
        }
-       return ret;
+
+       os->op = op;
+
+       ret = la_guid_from_dn(ac, op_dn, &os->guid);
+       if (ret == LDB_ERR_NO_SUCH_OBJECT && ac->req->operation == LDB_DELETE) {
+               /* we are deleting an object, and we've found it has a
+                * forward link to a target that no longer
+                * exists. This is not an error in the delete, and we
+                * should just not do the deferred delete of the
+                * target attribute
+                */
+               talloc_free(os);
+               return LDB_SUCCESS;
+       }
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       os->name = talloc_strdup(os, name);
+       if (!os->name) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       /* Do deletes before adds */
+       if (op == LA_OP_ADD) {
+               DLIST_ADD_END(ac->ops, os, struct la_op_store *);
+       } else {
+               /* By adding to the head of the list, we do deletes before
+                * adds when processing a replace */
+               DLIST_ADD(ac->ops, os);
+       }
+
+       return LDB_SUCCESS;
 }
 
+static int la_op_search_callback(struct ldb_request *req,
+                                struct ldb_reply *ares);
+static int la_queue_mod_request(struct la_context *ac);
+static int la_down_req(struct la_context *ac);
+
+
+
 /* add */
 static int linked_attributes_add(struct ldb_module *module, struct ldb_request *req)
 {
-       int i;
-       struct linked_attributes_context *ac;
+       struct ldb_context *ldb;
+       const struct dsdb_attribute *target_attr;
+       struct la_context *ac;
+       const char *attr_name;
+       int ret;
+       int i, j;
 
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       ldb = ldb_module_get_ctx(module);
 
-       if (ldb_dn_is_special(req->op.mod.message->dn)) {
+       if (ldb_dn_is_special(req->op.add.message->dn)) {
                /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
-
-       ac = linked_attributes_init_handle(req, module);
+       ac = linked_attributes_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       ac->step = LA_DO_OPS;
-       
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               talloc_free(ac);
+               return ldb_next_request(module, req);
+       }
+
        /* Need to ensure we only have forward links being specified */
        for (i=0; i < req->op.add.message->num_elements; i++) {
                const struct ldb_message_element *el = &req->op.add.message->elements[i];
                const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
+                       = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
                if (!schema_attr) {
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s is not a valid attribute in schema", req->op.add.message->elements[i].name);
+                       ldb_asprintf_errstring(ldb, 
+                                              "attribute %s is not a valid attribute in schema", el->name);
                        return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
                }
-               /* We have a valid attribute, not find out if it is linked */
+               /* We have a valid attribute, now find out if it is linked */
                if (schema_attr->linkID == 0) {
                        continue;
                }
                
                if ((schema_attr->linkID & 1) == 1) {
-                       /* Odd is for the target.  Illigal to modify */
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s must not be modified directly, it is a linked attribute", req->op.add.message->elements[i].name);
+                       /* Odd is for the target.  Illegal to modify */
+                       ldb_asprintf_errstring(ldb, 
+                                              "attribute %s must not be modified directly, it is a linked attribute", el->name);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
                
                /* Even link IDs are for the originating attribute */
-       }
-
-       /* Now call the common routine to setup the modifies across all the attributes */
-       return setup_modifies(module->ldb, ac, ac, req->op.add.message, NULL, req->op.add.message->dn);
-}
+               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+               if (!target_attr) {
+                       /*
+                        * windows 2003 has a broken schema where
+                        * the definition of msDS-IsDomainFor
+                        * is missing (which is supposed to be
+                        * the backlink of the msDS-HasDomainNCs
+                        * attribute
+                        */
+                       continue;
+               }
 
-struct merge {
-       struct ldb_dn *dn;
-       bool add;
-       bool ignore;
-};
+               attr_name = target_attr->lDAPDisplayName;
 
-static int merge_cmp(struct merge *merge1, struct merge *merge2) {
-       int ret;
-       ret = ldb_dn_compare(merge1->dn, merge2->dn);
-       if (ret == 0) {
-               if (merge1->add == merge2->add) {
-                       return 0;
-               }
-               if (merge1->add == true) {
-                       return 1;
+               for (j = 0; j < el->num_values; j++) {
+                       ret = la_store_op(ac, LA_OP_ADD,
+                                         &el->values[j],
+                                         attr_name);
+                       if (ret != LDB_SUCCESS) {
+                               return ret;
+                       }
                }
-               return -1;
        }
-       return ret;
+
+       /* if no linked attributes are present continue */
+       if (ac->ops == NULL) {
+               /* nothing to do for this module, proceed */
+               talloc_free(ac);
+               return ldb_next_request(module, req);
+       }
+
+       /* start with the original request */
+       return la_down_req(ac);
 }
 
-static int linked_attributes_mod_replace_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+/* For a delete or rename, we need to find out what linked attributes
+ * are currently on this DN, and then deal with them.  This is the
+ * callback to the base search */
+
+static int la_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       struct replace_context *ac2 = talloc_get_type(context, struct replace_context);
-       struct linked_attributes_context *ac = ac2->ac;
-    
-       /* OK, we have one search result here: */
+       struct ldb_context *ldb;
+       const struct dsdb_attribute *schema_attr;
+       const struct dsdb_attribute *target_attr;
+       struct ldb_message_element *search_el;
+       struct replace_context *rc;
+       struct la_context *ac;
+       const char *attr_name;
+       int i, j;
+       int ret = LDB_SUCCESS;
+
+       ac = talloc_get_type(req->context, struct la_context);
+       ldb = ldb_module_get_ctx(ac->module);
+       rc = ac->rc;
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
 
        /* Only entries are interesting, and we only want the olddn */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, ac->orig_req->op.mod.message->dn) == 0) {
-               /* only bother at all if there were some linked attributes found */
-               struct ldb_message_element *search_el
-                       = ldb_msg_find_element(ares->message,
-                                              ac2->el->name);
-               
-               /* See if this element already exists */
-               if (search_el) {
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
 
-                       struct merge *merged_list = NULL;
+               if (ldb_dn_compare(ares->message->dn, ac->req->op.mod.message->dn) != 0) {
+                       ldb_asprintf_errstring(ldb, 
+                                              "linked_attributes: %s is not the DN we were looking for", ldb_dn_get_linearized(ares->message->dn));
+                       /* Guh?  We only asked for this DN */
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
 
-                       int ret, size = 0, i;
-                       struct ldb_message *msg = ldb_msg_new(ac);
-                       if (!msg) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+               ac->add_dn = ac->del_dn = talloc_steal(ac, ares->message->dn);
 
-                       /* Add all the existing elements, marking as 'proposed for delete' by setting .add = false */
-                       for (i=0; i < search_el->num_values; i++) {
-                               merged_list = talloc_realloc(ares, merged_list, struct merge, size + 1);
-                               merged_list[size].dn = ldb_dn_new(merged_list, ldb, (char *)search_el->values[i].data);
-                               merged_list[size].add = false;
-                               merged_list[size].ignore = false;
-                               size++;
-                       }
+               /* We don't populate 'rc' for ADD - it can't be deleting elements anyway */
+               for (i = 0; rc && i < rc->num_elements; i++) {
 
-                       /* Add all the new replacement elements, marking as 'proposed for add' by setting .add = true */
-                       for (i=0; i < ac2->el->num_values; i++) {
-                               merged_list = talloc_realloc(ares, merged_list, struct merge, size + 1);
-                               merged_list[size].dn = ldb_dn_new(merged_list, ldb, (char *)ac2->el->values[i].data);
-                               merged_list[size].add = true;
-                               merged_list[size].ignore = false;
-                               size++;
+                       schema_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, rc->el[i].name);
+                       if (!schema_attr) {
+                               ldb_asprintf_errstring(ldb,
+                                       "attribute %s is not a valid attribute in schema",
+                                       rc->el[i].name);
+                               talloc_free(ares);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OBJECT_CLASS_VIOLATION);
                        }
 
-                       /* Sort the list, so we can pick out an add and delete for the same DN, and eliminate them */
-                       qsort(merged_list, size,
-                             sizeof(*merged_list),
-                             (comparison_fn_t)merge_cmp);
-
-                       /* Now things are sorted, it is trivial to mark pairs of DNs as 'ignore' */
-                       for (i=0; i + 1 < size; i++) {
-                               if (ldb_dn_compare(merged_list[i].dn, 
-                                                  merged_list[i+1].dn) == 0 
-                                   /* Fortunetly the sort also sorts 'add == false' first */
-                                   && merged_list[i].add == false
-                                   && merged_list[i+1].add == true) {
-
-                                       /* Mark as ignore, so we include neither in the actual operations */
-                                       merged_list[i].ignore = true;
-                                       merged_list[i+1].ignore = true;
-                               }
-                       }
+                       search_el = ldb_msg_find_element(ares->message,
+                                                        rc->el[i].name);
 
-                       /* Arrange to delete anything the search found that we don't re-add */
-                       for (i=0; i < size; i++) {
-                               if (merged_list[i].ignore == false
-                                   && merged_list[i].add == false) {
-                                       ldb_msg_add_steal_string(msg, search_el->name, 
-                                                                ldb_dn_get_linearized(merged_list[i].dn));
-                               }
+                       /* See if this element already exists */
+                       /* otherwise just ignore as
+                        * the add has already been scheduled */
+                       if ( ! search_el) {
+                               continue;
                        }
 
-                       /* The DN to set on the linked attributes is the original DN of the modify message */
-                       msg->dn = ac->orig_req->op.mod.message->dn;
-                       
-                       ret = setup_modifies(ac->module->ldb, ac2, ac, msg, ares->message->dn, NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+                       target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+                       if (!target_attr) {
+                               /*
+                                * windows 2003 has a broken schema where
+                                * the definition of msDS-IsDomainFor
+                                * is missing (which is supposed to be
+                                * the backlink of the msDS-HasDomainNCs
+                                * attribute
+                                */
+                               continue;
                        }
+                       attr_name = target_attr->lDAPDisplayName;
 
-                       /* Now add links for all the actually new elements */
-                       for (i=0; i < size; i++) {
-                               if (merged_list[i].ignore == false && merged_list[i].add == true) {
-                                       ldb_msg_add_steal_string(msg, search_el->name, 
-                                                                ldb_dn_get_linearized(merged_list[i].dn));
+                       /* Now we know what was there, we can remove it for the re-add */
+                       for (j = 0; j < search_el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_DEL,
+                                                 &search_el->values[j],
+                                                 attr_name);
+                               if (ret != LDB_SUCCESS) {
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
                                }
                        }
+               }
+
+               break;
+
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
+
+       case LDB_REPLY_DONE:
+
+               talloc_free(ares);
+
+               if (ac->req->operation == LDB_ADD) {
+                       /* Start the modifies to the backlinks */
+                       ret = la_queue_mod_request(ac);
 
-                       ret = setup_modifies(ac->module->ldb, ac2, ac, msg, NULL, ares->message->dn);
                        if (ret != LDB_SUCCESS) {
-                               return ret;
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                      ret);
                        }
-                       
-                       talloc_free(merged_list);
-
                } else {
-                       /* Looks like it doesn't exist, process like an 'add' */
-                       struct ldb_message *msg = ldb_msg_new(ac);
-                       if (!msg) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                       /* Start with the original request */
+                       ret = la_down_req(ac);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL, ret);
                        }
-                       msg->num_elements = 1;
-                       msg->elements = ac2->el;
-                       msg->dn = ac->orig_req->op.mod.message->dn;
-
-                       return setup_modifies(ac->module->ldb, ac2, ac, msg, NULL, ac->orig_req->op.mod.message->dn);
                }
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       } else if (ares->type == LDB_REPLY_ENTRY) {
-               /* Guh?  We only asked for this DN */
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       } else {
-               talloc_free(ares);
                return LDB_SUCCESS;
        }
-       
-       
+
+       talloc_free(ares);
+       return ret;
 }
+
+
 /* modify */
 static int linked_attributes_modify(struct ldb_module *module, struct ldb_request *req)
 {
@@ -430,501 +418,844 @@ static int linked_attributes_modify(struct ldb_module *module, struct ldb_reques
        /* Determine the effect of the modification */
        /* Apply the modify to the linked entry */
 
+       struct ldb_context *ldb;
        int i, j;
-       struct linked_attributes_context *ac;
+       struct la_context *ac;
+       struct ldb_request *search_req;
+       const char **attrs;
 
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       int ret;
+
+       ldb = ldb_module_get_ctx(module);
 
        if (ldb_dn_is_special(req->op.mod.message->dn)) {
                /* do not manipulate our control entries */
                return ldb_next_request(module, req);
        }
 
-
-       ac = linked_attributes_init_handle(req, module);
+       ac = linked_attributes_init(module, req);
        if (!ac) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
-       /* prepare the first operation */
-       ac->step = LA_DO_OPS;
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               return ldb_next_request(module, req);
+       }
+
+       ac->rc = talloc_zero(ac, struct replace_context);
+       if (!ac->rc) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
 
        for (i=0; i < req->op.mod.message->num_elements; i++) {
-               int ret;
-               struct ldb_request *new_req;
+               bool store_el = false;
+               const char *attr_name;
                const struct dsdb_attribute *target_attr;
                const struct ldb_message_element *el = &req->op.mod.message->elements[i];
                const struct dsdb_attribute *schema_attr
-                       = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
+                       = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
                if (!schema_attr) {
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s is not a valid attribute in schema", req->op.mod.message->elements[i].name);
+                       ldb_asprintf_errstring(ldb, 
+                                              "attribute %s is not a valid attribute in schema", el->name);
                        return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
                }
-               /* We have a valid attribute, not find out if it is linked */
+               /* We have a valid attribute, now find out if it is linked */
                if (schema_attr->linkID == 0) {
                        continue;
                }
                
                if ((schema_attr->linkID & 1) == 1) {
-                       /* Odd is for the target.  Illigal to modify */
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s must not be modified directly, it is a linked attribute", req->op.mod.message->elements[i].name);
+                       /* Odd is for the target.  Illegal to modify */
+                       ldb_asprintf_errstring(ldb, 
+                                              "attribute %s must not be modified directly, it is a linked attribute", el->name);
                        return LDB_ERR_UNWILLING_TO_PERFORM;
                }
                
                /* Even link IDs are for the originating attribute */
                
                /* Now find the target attribute */
-               target_attr = dsdb_attribute_by_linkID(schema, schema_attr->linkID + 1);
+               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
                if (!target_attr) {
-                       ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s does not have valid link target", req->op.mod.message->elements[i].name);
-                       return LDB_ERR_OBJECT_CLASS_VIOLATION;                  
+                       /*
+                        * windows 2003 has a broken schema where
+                        * the definition of msDS-IsDomainFor
+                        * is missing (which is supposed to be
+                        * the backlink of the msDS-HasDomainNCs
+                        * attribute
+                        */
+                       continue;
                }
 
-               /* Replace with new set of values */
-               if (((el->flags & LDB_FLAG_MOD_MASK) == LDB_FLAG_MOD_REPLACE)
-                   && el->num_values > 0) {
-                       struct replace_context *ac2 = talloc(ac, struct replace_context);
-                       const char **attrs = talloc_array(ac, const char *, 2);
-                       if (!attrs || !ac2) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       attrs[0] = el->name;
-                       attrs[1] = NULL;
-
-                       ac2->ac = ac;
-                       ac2->el = el;
+               attr_name = target_attr->lDAPDisplayName;
+       
+               switch (el->flags & LDB_FLAG_MOD_MASK) {
+               case LDB_FLAG_MOD_REPLACE:
+                       /* treat as just a normal add the delete part is handled by the callback */
+                       store_el = true;
 
-                       /* We need to setup a search, compare with the list, and then setup add/del as required */
-                       
-                       /* The callback does all the hard work here */
-                       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                                  req->op.mod.message->dn, 
-                                                  LDB_SCOPE_BASE,
-                                                  "(objectClass=*)",
-                                                  attrs,
-                                                  NULL, 
-                                                  ac2, 
-                                                  linked_attributes_mod_replace_search_callback);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, attrs);
-                       
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
+                       /* break intentionally missing */
 
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
+               case LDB_FLAG_MOD_ADD:
 
-                       ret = ldb_next_request(module, new_req);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+                       /* For each value being added, we need to setup the adds */
+                       for (j = 0; j < el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_ADD,
+                                                 &el->values[j],
+                                                 attr_name);
+                               if (ret != LDB_SUCCESS) {
+                                       return ret;
+                               }
                        }
-                       
-                       continue;
-
-                       /* Delete all values case */
-               } else if (((el->flags & LDB_FLAG_MOD_MASK) & (LDB_FLAG_MOD_DELETE|LDB_FLAG_MOD_REPLACE)) 
-                          && el->num_values == 0) {
-                       const char **attrs = talloc_array(ac, const char *, 2);
-                       if (!attrs) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+                       break;
+
+               case LDB_FLAG_MOD_DELETE:
+
+                       if (el->num_values) {
+                               /* For each value being deleted, we need to setup the delete */
+                               for (j = 0; j < el->num_values; j++) {
+                                       ret = la_store_op(ac, LA_OP_DEL,
+                                                         &el->values[j],
+                                                         attr_name);
+                                       if (ret != LDB_SUCCESS) {
+                                               return ret;
+                                       }
+                               }
+                       } else {
+                               /* Flag that there was a DELETE
+                                * without a value specified, so we
+                                * need to look for the old value */
+                               store_el = true;
                        }
-                       attrs[0] = el->name;
-                       attrs[1] = NULL;
 
-                       /* We need to setup a search, and then setup del as required */
-                       
-                       /* The callback does all the hard work here, acting identically to if we had delted the whole entry */
-                       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                                  req->op.mod.message->dn, 
-                                                  LDB_SCOPE_BASE,
-                                                  "(objectClass=*)",
-                                                  attrs,
-                                                  NULL, 
-                                                  ac, 
-                                                  linked_attributes_rename_del_search_callback);
+                       break;
+               }
 
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       talloc_steal(new_req, attrs);
-                       
-                       /* Create a spot in the list for the requests */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
+               if (store_el) {
+                       struct ldb_message_element *search_el;
+
+                       search_el = talloc_realloc(ac->rc, ac->rc->el,
+                                                  struct ldb_message_element,
+                                                  ac->rc->num_elements +1);
+                       if (!search_el) {
+                               ldb_oom(ldb);
                                return LDB_ERR_OPERATIONS_ERROR;
                        }
+                       ac->rc->el = search_el;
 
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
-                       
-                       ret = ldb_next_request(module, new_req);
+                       ac->rc->el[ac->rc->num_elements] = *el;
+                       ac->rc->num_elements++;
+               }
+       }
+       
+       if (ac->ops || ac->rc->el) {
+               /* both replace and delete without values are handled in the callback
+                * after the search on the entry to be modified is performed */
                
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
+               attrs = talloc_array(ac->rc, const char *, ac->rc->num_elements + 1);
+               if (!attrs) {
+                       ldb_oom(ldb);
+                       return LDB_ERR_OPERATIONS_ERROR;
+               }
+               for (i = 0; ac->rc && i < ac->rc->num_elements; i++) {
+                       attrs[i] = ac->rc->el[i].name;
+               }
+               attrs[i] = NULL;
+               
+               /* The callback does all the hard work here */
+               ret = ldb_build_search_req(&search_req, ldb, ac,
+                                          req->op.mod.message->dn,
+                                          LDB_SCOPE_BASE,
+                                          "(objectClass=*)", attrs,
+                                          NULL,
+                                          ac, la_mod_search_callback,
+                                          req);
+
+               /* We need to figure out our own extended DN, to fill in as the backlink target */
+               if (ret == LDB_SUCCESS) {
+                       ret = ldb_request_add_control(search_req,
+                                                     LDB_CONTROL_EXTENDED_DN_OID,
+                                                     false, NULL);
+               }
+               if (ret == LDB_SUCCESS) {
+                       talloc_steal(search_req, attrs);
                        
-                       continue;
+                       ret = ldb_next_request(module, search_req);
                }
 
-               /* Prepare the modify (mod element) on the targets, for a normal modify request */
+       } else {
+               /* nothing to do for this module, proceed */
+               talloc_free(ac);
+               ret = ldb_next_request(module, req);
+       }
 
-               /* For each value being moded, we need to setup the modify */
-               for (j=0; j < el->num_values; j++) {
-                       /* Create the modify request */
-                       struct ldb_message *new_msg = ldb_msg_new(ac);
-                       if (!new_msg) {
-                               ldb_oom(module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
-                       }
-                       new_msg->dn = ldb_dn_new(new_msg, module->ldb, (char *)el->values[j].data);
-                       if (!new_msg->dn) {
-                               ldb_asprintf_errstring(module->ldb, 
-                                              "attribute %s value %s was not a valid DN", req->op.mod.message->elements[i].name,
-                                                      el->values[j].data);
-                               return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
-                       }
+       return ret;
+}
 
-                       ret = ldb_msg_add_empty(new_msg, target_attr->lDAPDisplayName, 
-                                               el->flags & LDB_FLAG_MOD_MASK, NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
-                       }
-                       
-                       ret = ldb_msg_add_string(new_msg, target_attr->lDAPDisplayName, 
-                                                ldb_dn_get_linearized(ac->orig_req->op.add.message->dn));
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+/* delete */
+static int linked_attributes_del(struct ldb_module *module, struct ldb_request *req)
+{
+       struct ldb_context *ldb;
+       struct ldb_request *search_req;
+       struct la_context *ac;
+       const char **attrs;
+       WERROR werr;
+       int ret;
+
+       /* This gets complex:  We need to:
+          - Do a search for the entry
+          - Wait for these result to appear
+          - In the callback for the result, issue a modify
+               request based on the linked attributes found
+          - Wait for each modify result
+          - Regain our sainity
+       */
+
+       ldb = ldb_module_get_ctx(module);
+
+       ac = linked_attributes_init(module, req);
+       if (!ac) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               return ldb_next_request(module, req);
+       }
+
+       werr = dsdb_linked_attribute_lDAPDisplayName_list(ac->schema, ac, &attrs);
+       if (!W_ERROR_IS_OK(werr)) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       ret = ldb_build_search_req(&search_req, ldb, req,
+                                  req->op.del.dn, LDB_SCOPE_BASE,
+                                  "(objectClass=*)", attrs,
+                                  NULL,
+                                  ac, la_op_search_callback,
+                                  req);
+
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+
+       talloc_steal(search_req, attrs);
+
+       return ldb_next_request(module, search_req);
+}
+
+/* rename */
+static int linked_attributes_rename(struct ldb_module *module, struct ldb_request *req)
+{
+       struct la_context *ac;
+
+       /* This gets complex:  We need to:
+          - Do a search for the entry
+          - Wait for these result to appear
+          - In the callback for the result, issue a modify
+               request based on the linked attributes found
+          - Wait for each modify result
+          - Regain our sainity
+       */
+
+       ac = linked_attributes_init(module, req);
+       if (!ac) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+
+       if (!ac->schema) {
+               /* without schema, this doesn't make any sense */
+               return ldb_next_request(module, req);
+       }
+
+       /* start with the original request */
+       return la_down_req(ac);
+}
+
+
+static int la_op_search_callback(struct ldb_request *req,
+                                struct ldb_reply *ares)
+{
+       struct ldb_context *ldb;
+       struct la_context *ac;
+       const struct dsdb_attribute *schema_attr;
+       const struct dsdb_attribute *target_attr;
+       const struct ldb_message_element *el;
+       const char *attr_name;
+       int i, j;
+       int ret;
+
+       ac = talloc_get_type(req->context, struct la_context);
+       ldb = ldb_module_get_ctx(ac->module);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       /* Only entries are interesting, and we only want the olddn */
+       switch (ares->type) {
+       case LDB_REPLY_ENTRY:
+               ret = ldb_dn_compare(ares->message->dn, req->op.search.base);
+               if (ret != 0) {
+                       /* Guh?  We only asked for this DN */
+                       talloc_free(ares);
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+               if (ares->message->num_elements == 0) {
+                       /* only bother at all if there were some
+                        * linked attributes found */
+                       talloc_free(ares);
+                       return LDB_SUCCESS;
+               }
+
+               switch (ac->req->operation) {
+               case LDB_DELETE:
+                       ac->del_dn = talloc_steal(ac, ares->message->dn);
+                       break;
+               case LDB_RENAME:
+                       ac->add_dn = talloc_steal(ac, ares->message->dn); 
+                       ac->del_dn = talloc_steal(ac, ac->req->op.rename.olddn);
+                       break;
+               default:
+                       talloc_free(ares);
+                       ldb_set_errstring(ldb,
+                                         "operations must be delete or rename");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
+               }
+
+               for (i = 0; i < ares->message->num_elements; i++) {
+                       el = &ares->message->elements[i];
+
+                       schema_attr = dsdb_attribute_by_lDAPDisplayName(ac->schema, el->name);
+                       if (!schema_attr) {
+                               ldb_asprintf_errstring(ldb,
+                                       "attribute %s is not a valid attribute"
+                                       " in schema", el->name);
+                               talloc_free(ares);
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OBJECT_CLASS_VIOLATION);
                        }
 
-                       ret = ldb_build_mod_req(&new_req, module->ldb, ac,
-                                               new_msg,
-                                               NULL,
-                                               NULL,
-                                               NULL);
-                       if (ret != LDB_SUCCESS) {
-                               return ret;
+                       /* Valid attribute, now find out if it is linked */
+                       if (schema_attr->linkID == 0) {
+                               /* Not a linked attribute, skip */
+                               continue;
                        }
-                       
-                       talloc_steal(new_req, new_msg);
-                       
-                       ldb_set_timeout_from_prev_req(module->ldb, req, new_req);
-                       
-                       /* Now add it to the list */
-                       ac->down_req = talloc_realloc(ac, ac->down_req, 
-                                                     struct ldb_request *, ac->num_requests + 1);
-                       if (!ac->down_req) {
-                               ldb_oom(ac->module->ldb);
-                               return LDB_ERR_OPERATIONS_ERROR;
+
+                       if ((schema_attr->linkID & 1) == 0) {
+                               /* Odd is for the target. */
+                               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID + 1);
+                               if (!target_attr) {
+                                       continue;
+                               }
+                               attr_name = target_attr->lDAPDisplayName;
+                       } else {
+                               target_attr = dsdb_attribute_by_linkID(ac->schema, schema_attr->linkID - 1);
+                               if (!target_attr) {
+                                       continue;
+                               }
+                               attr_name = target_attr->lDAPDisplayName;
+                       }
+                       for (j = 0; j < el->num_values; j++) {
+                               ret = la_store_op(ac, LA_OP_DEL,
+                                                 &el->values[j],
+                                                 attr_name);
+
+                               /* for renames, ensure we add it back */
+                               if (ret == LDB_SUCCESS
+                                   && ac->req->operation == LDB_RENAME) {
+                                       ret = la_store_op(ac, LA_OP_ADD,
+                                                         &el->values[j],
+                                                         attr_name);
+                               }
+                               if (ret != LDB_SUCCESS) {
+                                       talloc_free(ares);
+                                       return ldb_module_done(ac->req,
+                                                              NULL, NULL, ret);
+                               }
                        }
-                       ac->down_req[ac->num_requests] = talloc_steal(ac->down_req, new_req);
-                       ac->num_requests++;
+               }
+
+               break;
 
-                       /* Run the new request */
-                       ret = ldb_next_request(module, new_req);
+       case LDB_REPLY_REFERRAL:
+               /* ignore */
+               break;
+
+       case LDB_REPLY_DONE:
+
+               talloc_free(ares);
+
+
+               switch (ac->req->operation) {
+               case LDB_DELETE:
+                       /* start the mod requests chain */
+                       ret = la_down_req(ac);
                        if (ret != LDB_SUCCESS) {
-                               return ret;
+                               return ldb_module_done(ac->req, NULL, NULL, ret);
                        }
+                       return ret;
+
+               case LDB_RENAME:        
+                       /* start the mod requests chain */
+                       ret = la_queue_mod_request(ac);
+                       if (ret != LDB_SUCCESS) {
+                               return ldb_module_done(ac->req, NULL, NULL,
+                                                      ret);
+                       }       
+                       return ret;
+                       
+               default:
+                       talloc_free(ares);
+                       ldb_set_errstring(ldb,
+                                         "operations must be delete or rename");
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                               LDB_ERR_OPERATIONS_ERROR);
                }
        }
+
+       talloc_free(ares);
        return LDB_SUCCESS;
 }
 
-static int linked_attributes_rename_del_search_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares) 
+/* queue a linked attributes modify request in the la_private
+   structure */
+static int la_queue_mod_request(struct la_context *ac)
 {
-       struct linked_attributes_context *ac = talloc_get_type(context, struct linked_attributes_context);
-       struct ldb_dn *olddn, *newdn;
-    
-       switch (ac->orig_req->operation) {
-       case LDB_DELETE:
-       {
-               olddn = ac->orig_req->op.del.dn;
-               newdn = NULL;
-               break;
-       } 
-       /* This isn't the general modify case, just the modify when we are asked to delete all values */
-       case LDB_MODIFY:
-       {
-               olddn = ac->orig_req->op.mod.message->dn;
-               newdn = NULL;
-               break;
-       } 
-       case LDB_RENAME:
-       {
-               olddn = ac->orig_req->op.rename.olddn;
-               newdn = ac->orig_req->op.rename.newdn;
-               break;
-       }       
-       default:
+       struct la_private *la_private = 
+               talloc_get_type(ldb_module_get_private(ac->module), struct la_private);
+
+       if (la_private == NULL) {
+               ldb_debug(ldb_module_get_ctx(ac->module), LDB_DEBUG_ERROR, __location__ ": No la_private transaction setup\n");
                return LDB_ERR_OPERATIONS_ERROR;
        }
-       
 
-       /* OK, we have one search result here: */
+       talloc_steal(la_private, ac);
+       DLIST_ADD(la_private->la_list, ac);
 
-       /* Only entries are interesting, and we only want the olddn */
-       if (ares->type == LDB_REPLY_ENTRY
-           && ldb_dn_compare(ares->message->dn, olddn) == 0) {
-               /* only bother at all if there were some linked attributes found */
-               if (ares->message->num_elements > 0) {
-                       return setup_modifies(ldb, ac, ac,
-                                             ares->message, olddn, newdn);
-               }
-               talloc_free(ares);
-               return LDB_SUCCESS;
-       } else if (ares->type == LDB_REPLY_ENTRY) {
-               /* Guh?  We only asked for this DN */
-               return LDB_ERR_OPERATIONS_ERROR;
+       return ldb_module_done(ac->req, ac->op_controls,
+                              ac->op_response, LDB_SUCCESS);
+}
 
-       } else {
+/* Having done the original operation, then try to fix up all the linked attributes for modify and delete */
+static int la_mod_del_callback(struct ldb_request *req, struct ldb_reply *ares)
+{
+       int ret;
+       struct la_context *ac;
+       struct ldb_context *ldb;
+
+       ac = talloc_get_type(req->context, struct la_context);
+       ldb = ldb_module_get_ctx(ac->module);
+
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ldb,
+                                 "invalid ldb_reply_type in callback");
                talloc_free(ares);
-               return LDB_SUCCESS;
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
        
+       ac->op_controls = talloc_steal(ac, ares->controls);
+       ac->op_response = talloc_steal(ac, ares->response);
+
+       /* If we have modfies to make, this is the time to do them for modify and delete */
+       ret = la_queue_mod_request(ac);
        
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL, ret);
+       }
+       talloc_free(ares);
+
+       /* la_queue_mod_request has already sent the callbacks */
+       return LDB_SUCCESS;
+
 }
-/* rename */
-static int linked_attributes_rename(struct ldb_module *module, struct ldb_request *req)
+
+/* Having done the original rename try to fix up all the linked attributes */
+static int la_rename_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       /* Look up list of linked attributes */
+       int ret;
+       struct la_context *ac;
+       struct ldb_request *search_req;
        const char **attrs;
        WERROR werr;
-       int ret;
-       struct linked_attributes_context *ac;
-       struct ldb_request *new_req;
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       struct ldb_context *ldb;
 
-       /* This gets complex:  We need to:
-          - Do a search for the entry 
-          - Wait for these result to appear
-          - In the callback for the result, issue a modify request based on the linked attributes found
-          - Wait for each modify result
-          - Regain our sainity 
-       */
+       ac = talloc_get_type(req->context, struct la_context);
+       ldb = ldb_module_get_ctx(ac->module);
 
-       ac = linked_attributes_init_handle(req, module);
-       if (!ac) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ldb,
+                                 "invalid ldb_reply_type in callback");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
        
-       werr = dsdb_linked_attribute_lDAPDisplayName_list(schema, ac, &attrs);
+       werr = dsdb_linked_attribute_lDAPDisplayName_list(ac->schema, ac, &attrs);
        if (!W_ERROR_IS_OK(werr)) {
                return LDB_ERR_OPERATIONS_ERROR;
        }
        
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                  req->op.rename.olddn, 
-                                  LDB_SCOPE_BASE,
-                                  "(objectClass=*)",
-                                  attrs,
-                                  NULL, 
-                                  ac, 
-                                  linked_attributes_rename_del_search_callback);
-
+       ret = ldb_build_search_req(&search_req, ldb, req,
+                                  ac->req->op.rename.newdn, LDB_SCOPE_BASE,
+                                  "(objectClass=*)", attrs,
+                                  NULL,
+                                  ac, la_op_search_callback,
+                                  req);
+       
        if (ret != LDB_SUCCESS) {
                return ret;
        }
+               
+       talloc_steal(search_req, attrs);
 
-       talloc_steal(new_req, attrs);
+       if (ret == LDB_SUCCESS) {
+               ret = ldb_request_add_control(search_req,
+                                             LDB_CONTROL_EXTENDED_DN_OID,
+                                             false, NULL);
+       }
+       if (ret != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                      ret);
+       }
+       
+       ac->op_controls = talloc_steal(ac, ares->controls);
+       ac->op_response = talloc_steal(ac, ares->response);
 
-       ac->search_req = new_req;
-       ac->step = LA_SEARCH;
-       return ldb_next_request(module, new_req);
+       return ldb_next_request(ac->module, search_req);
 }
 
-/* delete */
-static int linked_attributes_delete(struct ldb_module *module, struct ldb_request *req)
+/* Having done the original add, then try to fix up all the linked attributes
+
+  This is done after the add so the links can get the extended DNs correctly.
+ */
+static int la_add_callback(struct ldb_request *req, struct ldb_reply *ares)
 {
-       /* Look up list of linked attributes */
-       const char **attrs;
-       WERROR werr;
        int ret;
-       struct ldb_request *new_req;
-       struct linked_attributes_context *ac;
-       const struct dsdb_schema *schema = dsdb_get_schema(module->ldb);
-       if (!schema) {
-               /* without schema, this doesn't make any sense */
-               return ldb_next_request(module, req);
-       }
+       struct la_context *ac;
+       struct ldb_context *ldb;
 
-       /* This gets complex:  We need to:
-          - Do a search for the entry 
-          - Wait for these result to appear
-          - In the callback for the result, issue a modify request based on the linked attributes found
-          - Wait for each modify result
-          - Regain our sainity 
-       */
+       ac = talloc_get_type(req->context, struct la_context);
+       ldb = ldb_module_get_ctx(ac->module);
 
-       ac = linked_attributes_init_handle(req, module);
-       if (!ac) {
-               return LDB_ERR_OPERATIONS_ERROR;
+       if (!ares) {
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
+       }
+       if (ares->error != LDB_SUCCESS) {
+               return ldb_module_done(ac->req, ares->controls,
+                                       ares->response, ares->error);
+       }
+
+       if (ares->type != LDB_REPLY_DONE) {
+               ldb_set_errstring(ldb,
+                                 "invalid ldb_reply_type in callback");
+               talloc_free(ares);
+               return ldb_module_done(ac->req, NULL, NULL,
+                                       LDB_ERR_OPERATIONS_ERROR);
        }
        
-       werr = dsdb_linked_attribute_lDAPDisplayName_list(schema, ac, &attrs);
-       if (!W_ERROR_IS_OK(werr)) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       };
-       
-       ret = ldb_build_search_req(&new_req, module->ldb, req,
-                                  req->op.del.dn, 
-                                  LDB_SCOPE_BASE,
-                                  "(objectClass=*)",
-                                  attrs,
-                                  NULL, 
-                                  ac, 
-                                  linked_attributes_rename_del_search_callback);
+       if (ac->ops) {
+               struct ldb_request *search_req;
+               static const char *attrs[] = { NULL };
+               
+               /* The callback does all the hard work here - we need
+                * the objectGUID and SID of the added record */
+               ret = ldb_build_search_req(&search_req, ldb, ac,
+                                          ac->req->op.add.message->dn,
+                                          LDB_SCOPE_BASE,
+                                          "(objectClass=*)", attrs,
+                                          NULL,
+                                          ac, la_mod_search_callback,
+                                          ac->req);
+               
+               if (ret == LDB_SUCCESS) {
+                       ret = ldb_request_add_control(search_req,
+                                                     LDB_CONTROL_EXTENDED_DN_OID,
+                                                     false, NULL);
+               }
+               if (ret != LDB_SUCCESS) {
+                       return ldb_module_done(ac->req, NULL, NULL,
+                                              ret);
+               }
+
+               ac->op_controls = talloc_steal(ac, ares->controls);
+               ac->op_response = talloc_steal(ac, ares->response);
+
+               return ldb_next_request(ac->module, search_req);
+               
+       } else {
+               return ldb_module_done(ac->req, ares->controls,
+                                      ares->response, ares->error);
+       }
+}
+
+/* Reconstruct the original request, but pointing at our local callback to finish things off */
+static int la_down_req(struct la_context *ac)
+{
+       struct ldb_request *down_req;
+       int ret;
+       struct ldb_context *ldb;
 
+       ldb = ldb_module_get_ctx(ac->module);
+
+       switch (ac->req->operation) {
+       case LDB_ADD:
+               ret = ldb_build_add_req(&down_req, ldb, ac,
+                                       ac->req->op.add.message,
+                                       ac->req->controls,
+                                       ac, la_add_callback,
+                                       ac->req);
+               break;
+       case LDB_MODIFY:
+               ret = ldb_build_mod_req(&down_req, ldb, ac,
+                                       ac->req->op.mod.message,
+                                       ac->req->controls,
+                                       ac, la_mod_del_callback,
+                                       ac->req);
+               break;
+       case LDB_DELETE:
+               ret = ldb_build_del_req(&down_req, ldb, ac,
+                                       ac->req->op.del.dn,
+                                       ac->req->controls,
+                                       ac, la_mod_del_callback,
+                                       ac->req);
+               break;
+       case LDB_RENAME:
+               ret = ldb_build_rename_req(&down_req, ldb, ac,
+                                          ac->req->op.rename.olddn,
+                                          ac->req->op.rename.newdn,
+                                          ac->req->controls,
+                                          ac, la_rename_callback,
+                                          ac->req);
+               break;
+       default:
+               ret = LDB_ERR_OPERATIONS_ERROR;
+       }
        if (ret != LDB_SUCCESS) {
                return ret;
        }
 
-       talloc_steal(new_req, attrs);
+       return ldb_next_request(ac->module, down_req);
+}
 
-       ac->search_req = new_req;
-       ac->step = LA_SEARCH;
-       return ldb_next_request(module, new_req);
+/*
+  use the GUID part of an extended DN to find the target DN, in case
+  it has moved
+ */
+static int la_find_dn_target(struct ldb_module *module, struct la_context *ac, 
+                            struct GUID *guid, struct ldb_dn **dn)
+{
+       return dsdb_find_dn_by_guid(ldb_module_get_ctx(ac->module), ac, GUID_string(ac, guid), dn);
 }
 
+/* apply one la_context op change */
+static int la_do_op_request(struct ldb_module *module, struct la_context *ac, struct la_op_store *op)
+{
+       struct ldb_message_element *ret_el;
+       struct ldb_request *mod_req;
+       struct ldb_message *new_msg;
+       struct ldb_context *ldb;
+       int ret;
+
+       ldb = ldb_module_get_ctx(ac->module);
 
-static int linked_attributes_wait_none(struct ldb_handle *handle) {
-       struct linked_attributes_context *ac;
-       int i, ret = LDB_ERR_OPERATIONS_ERROR;
-       if (!handle || !handle->private_data) {
+       /* Create the modify request */
+       new_msg = ldb_msg_new(ac);
+       if (!new_msg) {
+               ldb_oom(ldb);
                return LDB_ERR_OPERATIONS_ERROR;
        }
 
-       if (handle->state == LDB_ASYNC_DONE) {
-               return handle->status;
+       ret = la_find_dn_target(module, ac, &op->guid, &new_msg->dn);
+       if (ret != LDB_SUCCESS) {
+               return ret;
        }
 
-       handle->state = LDB_ASYNC_PENDING;
-       handle->status = LDB_SUCCESS;
+       if (op->op == LA_OP_ADD) {
+               ret = ldb_msg_add_empty(new_msg, op->name,
+                                       LDB_FLAG_MOD_ADD, &ret_el);
+       } else {
+               ret = ldb_msg_add_empty(new_msg, op->name,
+                                       LDB_FLAG_MOD_DELETE, &ret_el);
+       }
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       ret_el->values = talloc_array(new_msg, struct ldb_val, 1);
+       if (!ret_el->values) {
+               ldb_oom(ldb);
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       ret_el->num_values = 1;
+       if (op->op == LA_OP_ADD) {
+               ret_el->values[0] = data_blob_string_const(ldb_dn_get_extended_linearized(new_msg, ac->add_dn, 1));
+       } else {
+               ret_el->values[0] = data_blob_string_const(ldb_dn_get_extended_linearized(new_msg, ac->del_dn, 1));
+       }
 
-       ac = talloc_get_type(handle->private_data, struct linked_attributes_context);
+#if 0
+       ldb_debug(ldb, LDB_DEBUG_WARNING,
+                 "link on %s %s: %s %s\n", 
+                 ldb_dn_get_linearized(new_msg->dn), ret_el->name, 
+                 ret_el->values[0].data, ac->ops->op == LA_OP_ADD ? "added" : "deleted");
+#endif 
+
+       ret = ldb_build_mod_req(&mod_req, ldb, op,
+                               new_msg,
+                               NULL,
+                               NULL, 
+                               ldb_op_default_callback,
+                               NULL);
+       if (ret != LDB_SUCCESS) {
+               return ret;
+       }
+       talloc_steal(mod_req, new_msg);
 
-       switch (ac->step) {
-       case LA_SEARCH:
-               ret = ldb_wait(ac->search_req->handle, LDB_WAIT_NONE);
-               
-               if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->search_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->search_req->handle->status;
-                       goto done;
-               }
-               
-               if (ac->search_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
-               }
-               ac->step = LA_DO_OPS;
-               return LDB_SUCCESS;
+       if (DEBUGLVL(4)) {
+               DEBUG(4,("Applying linked attribute change:\n%s\n",
+                        ldb_ldif_message_string(ldb, op, LDB_CHANGETYPE_MODIFY, new_msg)));
+       }
 
-       case LA_DO_OPS:
-               for (i=0; i < ac->num_requests; i++) {
-                       ret = ldb_wait(ac->down_req[i]->handle, LDB_WAIT_NONE);
-                       
-                       if (ret != LDB_SUCCESS) {
-                               handle->status = ret;
-                               goto done;
-                       }
-                       if (ac->down_req[i]->handle->status != LDB_SUCCESS) {
-                               handle->status = ac->down_req[i]->handle->status;
-                               goto done;
-                       }
-                       
-                       if (ac->down_req[i]->handle->state != LDB_ASYNC_DONE) {
-                               return LDB_SUCCESS;
-                       }
-               }
+       /* Run the new request */
+       ret = ldb_next_request(module, mod_req);
 
-               /* Now run the original request */
-               ac->step = LA_DO_ORIG;
-               return ldb_next_request(ac->module, ac->orig_down_req);
+       /* we need to wait for this to finish, as we are being called
+          from the synchronous end_transaction hook of this module */
+       if (ret == LDB_SUCCESS) {
+               ret = ldb_wait(mod_req->handle, LDB_WAIT_ALL);
+       }
 
-       case LA_DO_ORIG:
-               ret = ldb_wait(ac->orig_down_req->handle, LDB_WAIT_NONE);
-               
+       if (ret != LDB_SUCCESS) {
+               ldb_debug(ldb, LDB_DEBUG_WARNING, "Failed to apply linked attribute change '%s' %s\n",
+                         ldb_errstring(ldb),
+                         ldb_ldif_message_string(ldb, op, LDB_CHANGETYPE_MODIFY, new_msg));
+       }
+
+       return ret;
+}
+
+/* apply one set of la_context changes */
+static int la_do_mod_request(struct ldb_module *module, struct la_context *ac)
+{
+       struct la_op_store *op;
+
+       for (op = ac->ops; op; op=op->next) {
+               int ret = la_do_op_request(module, ac, op);
                if (ret != LDB_SUCCESS) {
-                       handle->status = ret;
-                       goto done;
-               }
-               if (ac->orig_down_req->handle->status != LDB_SUCCESS) {
-                       handle->status = ac->orig_down_req->handle->status;
-                       goto done;
-               }
-               
-               if (ac->orig_down_req->handle->state != LDB_ASYNC_DONE) {
-                       return LDB_SUCCESS;
+                       if (ret != LDB_ERR_NO_SUCH_OBJECT) {
+                               return ret;
+                       }
                }
-               ret = LDB_SUCCESS;
        }
 
-done:
-       handle->state = LDB_ASYNC_DONE;
-       return ret;
+       return LDB_SUCCESS;
+}
 
+
+/*
+  we hook into the transaction operations to allow us to 
+  perform the linked attribute updates at the end of the whole
+  transaction. This allows a forward linked attribute to be created
+  before the target is created, as long as the target is created
+  in the same transaction
+ */
+static int linked_attributes_start_transaction(struct ldb_module *module)
+{
+       /* create our private structure for this transaction */
+       struct la_private *la_private = talloc_get_type(ldb_module_get_private(module),
+                                                       struct la_private);
+       talloc_free(la_private);
+       la_private = talloc(module, struct la_private);
+       if (la_private == NULL) {
+               return LDB_ERR_OPERATIONS_ERROR;
+       }
+       la_private->la_list = NULL;
+       ldb_module_set_private(module, la_private);
+       return ldb_next_start_trans(module);
 }
 
-static int linked_attributes_wait_all(struct ldb_handle *handle) {
+/*
+  on prepare commit we loop over our queued la_context structures
+  and apply each of them
+ */
+static int linked_attributes_prepare_commit(struct ldb_module *module)
+{
+       struct la_private *la_private = 
+               talloc_get_type(ldb_module_get_private(module), struct la_private);
+       struct la_context *ac;
 
-       int ret;
+       if (!la_private) {
+               /* prepare commit without begin_transaction - let someone else return the error, just don't segfault */
+               return ldb_next_prepare_commit(module);
+       }
+       /* walk the list backwards, to do the first entry first, as we
+        * added the entries with DLIST_ADD() which puts them at the
+        * start of the list */
+       for (ac = la_private->la_list; ac && ac->next; ac=ac->next) ;
 
-       while (handle->state != LDB_ASYNC_DONE) {
-               ret = linked_attributes_wait_none(handle);
+       for (; ac; ac=ac->prev) {
+               int ret;
+               ac->req = NULL;
+               ret = la_do_mod_request(module, ac);
                if (ret != LDB_SUCCESS) {
+                       DEBUG(0,(__location__ ": Failed mod request ret=%d\n", ret));
+                       talloc_free(la_private);
+                       ldb_module_set_private(module, NULL);   
                        return ret;
                }
        }
 
-       return handle->status;
+       talloc_free(la_private);
+       ldb_module_set_private(module, NULL);   
+
+       return ldb_next_prepare_commit(module);
 }
 
-static int linked_attributes_wait(struct ldb_handle *handle, enum ldb_wait_type type)
+static int linked_attributes_del_transaction(struct ldb_module *module)
 {
-       if (type == LDB_WAIT_ALL) {
-               return linked_attributes_wait_all(handle);
-       } else {
-               return linked_attributes_wait_none(handle);
-       }
+       struct la_private *la_private = 
+               talloc_get_type(ldb_module_get_private(module), struct la_private);
+       talloc_free(la_private);
+       ldb_module_set_private(module, NULL);
+       return ldb_next_del_trans(module);
 }
 
-static const struct ldb_module_ops linked_attributes_ops = {
+
+_PUBLIC_ const struct ldb_module_ops ldb_linked_attributes_module_ops = {
        .name              = "linked_attributes",
        .add               = linked_attributes_add,
        .modify            = linked_attributes_modify,
-       .del               = linked_attributes_delete,
+       .del               = linked_attributes_del,
        .rename            = linked_attributes_rename,
-       .wait              = linked_attributes_wait,
+       .start_transaction = linked_attributes_start_transaction,
+       .prepare_commit    = linked_attributes_prepare_commit,
+       .del_transaction   = linked_attributes_del_transaction,
 };
-
-int ldb_linked_attributes_init(void)
-{
-       return ldb_register_module(&linked_attributes_ops);
-}