dsdb: Take out the transaction and prepare_commit locks in the same order
[sfrench/samba-autobuild/.git] / source4 / dsdb / samdb / ldb_modules / partition.c
1 /* 
2    Partitions ldb module
3
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
5    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22  *  Name: ldb
23  *
24  *  Component: ldb partitions module
25  *
26  *  Description: Implement LDAP partitions
27  *
28  *  Author: Andrew Bartlett
29  *  Author: Stefan Metzmacher
30  */
31
32 #include "dsdb/samdb/ldb_modules/partition.h"
33
34 struct part_request {
35         struct ldb_module *module;
36         struct ldb_request *req;
37 };
38
39 struct partition_context {
40         struct ldb_module *module;
41         struct ldb_request *req;
42
43         struct part_request *part_req;
44         unsigned int num_requests;
45         unsigned int finished_requests;
46
47         const char **referrals;
48 };
49
50 static struct partition_context *partition_init_ctx(struct ldb_module *module, struct ldb_request *req)
51 {
52         struct partition_context *ac;
53
54         ac = talloc_zero(req, struct partition_context);
55         if (ac == NULL) {
56                 ldb_set_errstring(ldb_module_get_ctx(module), "Out of Memory");
57                 return NULL;
58         }
59
60         ac->module = module;
61         ac->req = req;
62
63         return ac;
64 }
65
66 /*
67  * helper functions to call the next module in chain
68  */
69 int partition_request(struct ldb_module *module, struct ldb_request *request)
70 {
71         if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) { \
72                 const struct dsdb_control_current_partition *partition = NULL;
73                 struct ldb_control *partition_ctrl = ldb_request_get_control(request, DSDB_CONTROL_CURRENT_PARTITION_OID);
74                 if (partition_ctrl) {
75                         partition = talloc_get_type(partition_ctrl->data,
76                                                     struct dsdb_control_current_partition);
77                 }
78
79                 if (partition != NULL) {
80                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_request() -> %s",
81                                   ldb_dn_get_linearized(partition->dn));                        
82                 } else {
83                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_request() -> (metadata partition)");
84                 }
85         }
86
87         return ldb_next_request(module, request);
88 }
89
90 static struct dsdb_partition *find_partition(struct partition_private_data *data,
91                                              struct ldb_dn *dn,
92                                              struct ldb_request *req)
93 {
94         unsigned int i;
95         struct ldb_control *partition_ctrl;
96
97         /* see if the request has the partition DN specified in a
98          * control. The repl_meta_data module can specify this to
99          * ensure that replication happens to the right partition
100          */
101         partition_ctrl = ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID);
102         if (partition_ctrl) {
103                 const struct dsdb_control_current_partition *partition;
104                 partition = talloc_get_type(partition_ctrl->data,
105                                             struct dsdb_control_current_partition);
106                 if (partition != NULL) {
107                         dn = partition->dn;
108                 }
109         }
110
111         if (dn == NULL) {
112                 return NULL;
113         }
114
115         /* Look at base DN */
116         /* Figure out which partition it is under */
117         /* Skip the lot if 'data' isn't here yet (initialisation) */
118         for (i=0; data && data->partitions && data->partitions[i]; i++) {
119                 if (ldb_dn_compare_base(data->partitions[i]->ctrl->dn, dn) == 0) {
120                         return data->partitions[i];
121                 }
122         }
123
124         return NULL;
125 }
126
127 /**
128  * fire the caller's callback for every entry, but only send 'done' once.
129  */
130 static int partition_req_callback(struct ldb_request *req,
131                                   struct ldb_reply *ares)
132 {
133         struct partition_context *ac;
134         struct ldb_module *module;
135         struct ldb_request *nreq;
136         int ret;
137         struct ldb_control *partition_ctrl;
138
139         ac = talloc_get_type(req->context, struct partition_context);
140
141         if (!ares) {
142                 return ldb_module_done(ac->req, NULL, NULL,
143                                         LDB_ERR_OPERATIONS_ERROR);
144         }
145
146         partition_ctrl = ldb_request_get_control(req, DSDB_CONTROL_CURRENT_PARTITION_OID);
147         if (partition_ctrl && (ac->num_requests == 1 || ares->type == LDB_REPLY_ENTRY)) {
148                 /* If we didn't fan this request out to mulitple partitions,
149                  * or this is an individual search result, we can
150                  * deterministically tell the caller what partition this was
151                  * written to (repl_meta_data likes to know) */
152                 ret = ldb_reply_add_control(ares,
153                                             DSDB_CONTROL_CURRENT_PARTITION_OID,
154                                             false, partition_ctrl->data);
155                 if (ret != LDB_SUCCESS) {
156                         return ldb_module_done(ac->req, NULL, NULL,
157                                                ret);
158                 }
159         }
160
161         if (ares->error != LDB_SUCCESS) {
162                 return ldb_module_done(ac->req, ares->controls,
163                                         ares->response, ares->error);
164         }
165
166         switch (ares->type) {
167         case LDB_REPLY_REFERRAL:
168                 return ldb_module_send_referral(ac->req, ares->referral);
169
170         case LDB_REPLY_ENTRY:
171                 if (ac->req->operation != LDB_SEARCH) {
172                         ldb_set_errstring(ldb_module_get_ctx(ac->module),
173                                 "partition_req_callback:"
174                                 " Unsupported reply type for this request");
175                         return ldb_module_done(ac->req, NULL, NULL,
176                                                 LDB_ERR_OPERATIONS_ERROR);
177                 }
178                 
179                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
180
181         case LDB_REPLY_DONE:
182                 if (ac->req->operation == LDB_EXTENDED) {
183                         /* FIXME: check for ares->response, replmd does not fill it ! */
184                         if (ares->response) {
185                                 if (strcmp(ares->response->oid, LDB_EXTENDED_START_TLS_OID) != 0) {
186                                         ldb_set_errstring(ldb_module_get_ctx(ac->module),
187                                                           "partition_req_callback:"
188                                                           " Unknown extended reply, "
189                                                           "only supports START_TLS");
190                                         talloc_free(ares);
191                                         return ldb_module_done(ac->req, NULL, NULL,
192                                                                 LDB_ERR_OPERATIONS_ERROR);
193                                 }
194                         }
195                 }
196
197                 ac->finished_requests++;
198                 if (ac->finished_requests == ac->num_requests) {
199                         /* Send back referrals if they do exist (search ops) */
200                         if (ac->referrals != NULL) {
201                                 const char **ref;
202                                 for (ref = ac->referrals; *ref != NULL; ++ref) {
203                                         ret = ldb_module_send_referral(ac->req,
204                                                                        talloc_strdup(ac->req, *ref));
205                                         if (ret != LDB_SUCCESS) {
206                                                 return ldb_module_done(ac->req, NULL, NULL,
207                                                                        ret);
208                                         }
209                                 }
210                         }
211
212                         /* this was the last one, call callback */
213                         return ldb_module_done(ac->req, ares->controls,
214                                                ares->response, 
215                                                ares->error);
216                 }
217
218                 /* not the last, now call the next one */
219                 module = ac->part_req[ac->finished_requests].module;
220                 nreq = ac->part_req[ac->finished_requests].req;
221
222                 ret = partition_request(module, nreq);
223                 if (ret != LDB_SUCCESS) {
224                         talloc_free(ares);
225                         return ldb_module_done(ac->req, NULL, NULL, ret);
226                 }
227
228                 break;
229         }
230
231         talloc_free(ares);
232         return LDB_SUCCESS;
233 }
234
235 static int partition_prep_request(struct partition_context *ac,
236                                   struct dsdb_partition *partition)
237 {
238         int ret;
239         struct ldb_request *req;
240         struct ldb_control *partition_ctrl = NULL;
241
242         ac->part_req = talloc_realloc(ac, ac->part_req,
243                                         struct part_request,
244                                         ac->num_requests + 1);
245         if (ac->part_req == NULL) {
246                 return ldb_oom(ldb_module_get_ctx(ac->module));
247         }
248
249         switch (ac->req->operation) {
250         case LDB_SEARCH:
251                 ret = ldb_build_search_req_ex(&req, ldb_module_get_ctx(ac->module),
252                                         ac->part_req,
253                                         ac->req->op.search.base,
254                                         ac->req->op.search.scope,
255                                         ac->req->op.search.tree,
256                                         ac->req->op.search.attrs,
257                                         ac->req->controls,
258                                         ac, partition_req_callback,
259                                         ac->req);
260                 LDB_REQ_SET_LOCATION(req);
261                 break;
262         case LDB_ADD:
263                 ret = ldb_build_add_req(&req, ldb_module_get_ctx(ac->module), ac->part_req,
264                                         ac->req->op.add.message,
265                                         ac->req->controls,
266                                         ac, partition_req_callback,
267                                         ac->req);
268                 LDB_REQ_SET_LOCATION(req);
269                 break;
270         case LDB_MODIFY:
271                 ret = ldb_build_mod_req(&req, ldb_module_get_ctx(ac->module), ac->part_req,
272                                         ac->req->op.mod.message,
273                                         ac->req->controls,
274                                         ac, partition_req_callback,
275                                         ac->req);
276                 LDB_REQ_SET_LOCATION(req);
277                 break;
278         case LDB_DELETE:
279                 ret = ldb_build_del_req(&req, ldb_module_get_ctx(ac->module), ac->part_req,
280                                         ac->req->op.del.dn,
281                                         ac->req->controls,
282                                         ac, partition_req_callback,
283                                         ac->req);
284                 LDB_REQ_SET_LOCATION(req);
285                 break;
286         case LDB_RENAME:
287                 ret = ldb_build_rename_req(&req, ldb_module_get_ctx(ac->module), ac->part_req,
288                                         ac->req->op.rename.olddn,
289                                         ac->req->op.rename.newdn,
290                                         ac->req->controls,
291                                         ac, partition_req_callback,
292                                         ac->req);
293                 LDB_REQ_SET_LOCATION(req);
294                 break;
295         case LDB_EXTENDED:
296                 ret = ldb_build_extended_req(&req, ldb_module_get_ctx(ac->module),
297                                         ac->part_req,
298                                         ac->req->op.extended.oid,
299                                         ac->req->op.extended.data,
300                                         ac->req->controls,
301                                         ac, partition_req_callback,
302                                         ac->req);
303                 LDB_REQ_SET_LOCATION(req);
304                 break;
305         default:
306                 ldb_set_errstring(ldb_module_get_ctx(ac->module),
307                                   "Unsupported request type!");
308                 ret = LDB_ERR_UNWILLING_TO_PERFORM;
309         }
310
311         if (ret != LDB_SUCCESS) {
312                 return ret;
313         }
314
315         ac->part_req[ac->num_requests].req = req;
316
317         if (ac->req->controls) {
318                 /* Duplicate everything beside the current partition control */
319                 partition_ctrl = ldb_request_get_control(ac->req,
320                                                          DSDB_CONTROL_CURRENT_PARTITION_OID);
321                 if (!ldb_save_controls(partition_ctrl, req, NULL)) {
322                         return ldb_module_oom(ac->module);
323                 }
324         }
325
326         if (partition) {
327                 void *part_data = partition->ctrl;
328
329                 ac->part_req[ac->num_requests].module = partition->module;
330
331                 if (partition_ctrl != NULL) {
332                         if (partition_ctrl->data != NULL) {
333                                 part_data = partition_ctrl->data;
334                         }
335
336                         /*
337                          * If the provided current partition control is without
338                          * data then use the calculated one.
339                          */
340                         ret = ldb_request_add_control(req,
341                                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
342                                                       false, part_data);
343                         if (ret != LDB_SUCCESS) {
344                                 return ret;
345                         }
346                 }
347
348                 if (req->operation == LDB_SEARCH) {
349                         /* If the search is for 'more' than this partition,
350                          * then change the basedn, so a remote LDAP server
351                          * doesn't object */
352                         if (ldb_dn_compare_base(partition->ctrl->dn,
353                                                 req->op.search.base) != 0) {
354                                 req->op.search.base = partition->ctrl->dn;
355                         }
356                 }
357
358         } else {
359                 /* make sure you put the module here, or
360                  * or ldb_next_request() will skip a module */
361                 ac->part_req[ac->num_requests].module = ac->module;
362         }
363
364         ac->num_requests++;
365
366         return LDB_SUCCESS;
367 }
368
369 static int partition_call_first(struct partition_context *ac)
370 {
371         return partition_request(ac->part_req[0].module, ac->part_req[0].req);
372 }
373
374 /**
375  * Send a request down to all the partitions
376  */
377 static int partition_send_all(struct ldb_module *module, 
378                               struct partition_context *ac, 
379                               struct ldb_request *req) 
380 {
381         unsigned int i;
382         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
383                                                               struct partition_private_data);
384         int ret = partition_prep_request(ac, NULL);
385         if (ret != LDB_SUCCESS) {
386                 return ret;
387         }
388         for (i=0; data && data->partitions && data->partitions[i]; i++) {
389                 ret = partition_prep_request(ac, data->partitions[i]);
390                 if (ret != LDB_SUCCESS) {
391                         return ret;
392                 }
393         }
394
395         /* fire the first one */
396         return partition_call_first(ac);
397 }
398
399
400 /**
401  * send an operation to the top partition, then copy the resulting
402  * object to all other partitions
403  */
404 static int partition_copy_all(struct ldb_module *module,
405                               struct partition_context *ac,
406                               struct ldb_request *req,
407                               struct ldb_dn *dn)
408 {
409         unsigned int i;
410         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
411                                                               struct partition_private_data);
412         int ret, search_ret;
413         struct ldb_result *res;
414
415         /* do the request on the top level sam.ldb synchronously */
416         ret = ldb_next_request(module, req);
417         if (ret != LDB_SUCCESS) {
418                 return ret;
419         }
420         ret = ldb_wait(req->handle, LDB_WAIT_ALL);
421         if (ret != LDB_SUCCESS) {
422                 return ret;
423         }
424
425         /* now fetch the resulting object, and then copy it to all the
426          * other partitions. We need this approach to cope with the
427          * partitions getting out of sync. If for example the
428          * @ATTRIBUTES object exists on one partition but not the
429          * others then just doing each of the partitions in turn will
430          * lead to an error
431          */
432         search_ret = dsdb_module_search_dn(module, ac, &res, dn, NULL, DSDB_FLAG_NEXT_MODULE, req);
433         if (search_ret != LDB_SUCCESS && ret != LDB_ERR_NO_SUCH_OBJECT) {
434                 return search_ret;
435         }
436
437         /* now delete the object in the other partitions. Once that is
438            done we will re-add the object, if search_ret was not
439            LDB_ERR_NO_SUCH_OBJECT
440         */
441         for (i=0; data->partitions && data->partitions[i]; i++) {
442                 int pret;
443                 pret = dsdb_module_del(data->partitions[i]->module, dn, DSDB_FLAG_NEXT_MODULE, req);
444                 if (pret != LDB_SUCCESS && pret != LDB_ERR_NO_SUCH_OBJECT) {
445                         /* we should only get success or no
446                            such object from the other partitions */
447                         return pret;
448                 }
449         }
450
451
452         if (search_ret != LDB_ERR_NO_SUCH_OBJECT) {
453                 /* now re-add in the other partitions */
454                 for (i=0; data->partitions && data->partitions[i]; i++) {
455                         int pret;
456                         pret = dsdb_module_add(data->partitions[i]->module, res->msgs[0], DSDB_FLAG_NEXT_MODULE, req);
457                         if (pret != LDB_SUCCESS) {
458                                 return pret;
459                         }
460                 }
461         }
462
463         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
464 }
465
466 /**
467  * Figure out which backend a request needs to be aimed at.  Some
468  * requests must be replicated to all backends
469  */
470 static int partition_replicate(struct ldb_module *module, struct ldb_request *req, struct ldb_dn *dn) 
471 {
472         struct partition_context *ac;
473         unsigned int i;
474         int ret;
475         struct dsdb_partition *partition;
476         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
477                                                               struct partition_private_data);
478
479         /* if we aren't initialised yet go further */
480         if (!data || !data->partitions) {
481                 return ldb_next_request(module, req);
482         }
483
484         if (ldb_dn_is_special(dn)) {
485                 /* Is this a special DN, we need to replicate to every backend? */
486                 for (i=0; data->replicate && data->replicate[i]; i++) {
487                         if (ldb_dn_compare(data->replicate[i], 
488                                            dn) == 0) {
489                                 
490                                 ac = partition_init_ctx(module, req);
491                                 if (!ac) {
492                                         return ldb_operr(ldb_module_get_ctx(module));
493                                 }
494                                 
495                                 return partition_copy_all(module, ac, req, dn);
496                         }
497                 }
498         }
499
500         /* Otherwise, we need to find the partition to fire it to */
501
502         /* Find partition */
503         partition = find_partition(data, dn, req);
504         if (!partition) {
505                 /*
506                  * if we haven't found a matching partition
507                  * pass the request to the main ldb
508                  *
509                  * TODO: we should maybe return an error here
510                  *       if it's not a special dn
511                  */
512
513                 return ldb_next_request(module, req);
514         }
515
516         ac = partition_init_ctx(module, req);
517         if (!ac) {
518                 return ldb_operr(ldb_module_get_ctx(module));
519         }
520
521         /* we need to add a control but we never touch the original request */
522         ret = partition_prep_request(ac, partition);
523         if (ret != LDB_SUCCESS) {
524                 return ret;
525         }
526
527         /* fire the first one */
528         return partition_call_first(ac);
529 }
530
531 /* search */
532 static int partition_search(struct ldb_module *module, struct ldb_request *req)
533 {
534         struct ldb_control **saved_controls;
535         /* Find backend */
536         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
537                                                               struct partition_private_data);
538         struct partition_context *ac;
539         struct ldb_context *ldb;
540         struct loadparm_context *lp_ctx;
541
542         struct ldb_control *search_control = ldb_request_get_control(req, LDB_CONTROL_SEARCH_OPTIONS_OID);
543         struct ldb_control *domain_scope_control = ldb_request_get_control(req, LDB_CONTROL_DOMAIN_SCOPE_OID);
544         struct ldb_control *no_gc_control = ldb_request_get_control(req, DSDB_CONTROL_NO_GLOBAL_CATALOG);
545         
546         struct ldb_search_options_control *search_options = NULL;
547         struct dsdb_partition *p;
548         unsigned int i, j;
549         int ret;
550         bool domain_scope = false, phantom_root = false;
551
552         p = find_partition(data, NULL, req);
553         if (p != NULL) {
554                 /* the caller specified what partition they want the
555                  * search - just pass it on
556                  */
557                 return ldb_next_request(p->module, req);
558         }
559
560         /* Get back the search options from the search control, and mark it as
561          * non-critical (to make backends and also dcpromo happy).
562          */
563         if (search_control) {
564                 search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
565                 search_control->critical = 0;
566
567         }
568
569         /* Remove the "domain_scope" control, so we don't confuse a backend
570          * server */
571         if (domain_scope_control && !ldb_save_controls(domain_scope_control, req, &saved_controls)) {
572                 return ldb_oom(ldb_module_get_ctx(module));
573         }
574
575         /* if we aren't initialised yet go further */
576         if (!data || !data->partitions) {
577                 return ldb_next_request(module, req);
578         }
579
580         /* Special DNs without specified partition should go further */
581         if (ldb_dn_is_special(req->op.search.base)) {
582                 return ldb_next_request(module, req);
583         }
584
585         /* Locate the options */
586         domain_scope = (search_options
587                 && (search_options->search_options & LDB_SEARCH_OPTION_DOMAIN_SCOPE))
588                 || domain_scope_control;
589         phantom_root = search_options
590                 && (search_options->search_options & LDB_SEARCH_OPTION_PHANTOM_ROOT);
591
592         /* Remove handled options from the search control flag */
593         if (search_options) {
594                 search_options->search_options = search_options->search_options
595                         & ~LDB_SEARCH_OPTION_DOMAIN_SCOPE
596                         & ~LDB_SEARCH_OPTION_PHANTOM_ROOT;
597         }
598
599         ac = partition_init_ctx(module, req);
600         if (!ac) {
601                 return ldb_operr(ldb_module_get_ctx(module));
602         }
603
604         ldb = ldb_module_get_ctx(ac->module);
605         lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
606                                                 struct loadparm_context);
607
608         /* Search from the base DN */
609         if (ldb_dn_is_null(req->op.search.base)) {
610                 if (!phantom_root) {
611                         return ldb_error(ldb, LDB_ERR_NO_SUCH_OBJECT, "empty base DN");
612                 }
613                 return partition_send_all(module, ac, req);
614         }
615
616         for (i=0; data->partitions[i]; i++) {
617                 bool match = false, stop = false;
618
619                 if (data->partitions[i]->partial_replica && no_gc_control != NULL) {
620                         if (ldb_dn_compare_base(data->partitions[i]->ctrl->dn,
621                                                 req->op.search.base) == 0) {
622                                 /* base DN is in a partial replica
623                                    with the NO_GLOBAL_CATALOG
624                                    control. This partition is invisible */
625                                 /* DEBUG(0,("DENYING NON-GC OP: %s\n", ldb_module_call_chain(req, req))); */
626                                 continue;
627                         }
628                 }
629
630                 if (phantom_root) {
631                         /* Phantom root: Find all partitions under the
632                          * search base. We match if:
633                          *
634                          * 1) the DN we are looking for exactly matches a
635                          *    certain partition and always stop
636                          * 2) the DN we are looking for is a parent of certain
637                          *    partitions and it isn't a scope base search
638                          * 3) the DN we are looking for is a child of a certain
639                          *    partition and always stop
640                          *    - we don't need to go any further up in the
641                          *    hierarchy!
642                          */
643                         if (ldb_dn_compare(data->partitions[i]->ctrl->dn,
644                                            req->op.search.base) == 0) {
645                                 match = true;
646                                 stop = true;
647                         }
648                         if (!match &&
649                             (ldb_dn_compare_base(req->op.search.base,
650                                                  data->partitions[i]->ctrl->dn) == 0 &&
651                              req->op.search.scope != LDB_SCOPE_BASE)) {
652                                 match = true;
653                         }
654                         if (!match &&
655                             ldb_dn_compare_base(data->partitions[i]->ctrl->dn,
656                                                 req->op.search.base) == 0) {
657                                 match = true;
658                                 stop = true; /* note that this relies on partition ordering */
659                         }
660                 } else {
661                         /* Domain scope: Find all partitions under the search
662                          * base.
663                          *
664                          * We generate referral candidates if we haven't
665                          * specified the domain scope control, haven't a base
666                          * search* scope and the DN we are looking for is a real
667                          * predecessor of certain partitions. When a new
668                          * referral candidate is nearer to the DN than an
669                          * existing one delete the latter (we want to have only
670                          * the closest ones). When we checked this for all
671                          * candidates we have the final referrals.
672                          *
673                          * We match if the DN we are looking for is a child of
674                          * a certain partition or the partition
675                          * DN itself - we don't need to go any further
676                          * up in the hierarchy!
677                          */
678                         if ((!domain_scope) &&
679                             (req->op.search.scope != LDB_SCOPE_BASE) &&
680                             (ldb_dn_compare_base(req->op.search.base,
681                                                  data->partitions[i]->ctrl->dn) == 0) &&
682                             (ldb_dn_compare(req->op.search.base,
683                                             data->partitions[i]->ctrl->dn) != 0)) {
684                                 char *ref = talloc_asprintf(ac,
685                                                             "ldap://%s/%s%s",
686                                                             lpcfg_dnsdomain(lp_ctx),
687                                                             ldb_dn_get_linearized(data->partitions[i]->ctrl->dn),
688                                                             req->op.search.scope == LDB_SCOPE_ONELEVEL ? "??base" : "");
689
690                                 if (ref == NULL) {
691                                         return ldb_oom(ldb);
692                                 }
693
694                                 /* Initialise the referrals list */
695                                 if (ac->referrals == NULL) {
696                                         char **l = str_list_make_empty(ac);
697                                         ac->referrals = discard_const_p(const char *, l);
698                                         if (ac->referrals == NULL) {
699                                                 return ldb_oom(ldb);
700                                         }
701                                 }
702
703                                 /* Check if the new referral candidate is
704                                  * closer to the base DN than already
705                                  * saved ones and delete the latters */
706                                 j = 0;
707                                 while (ac->referrals[j] != NULL) {
708                                         if (strstr(ac->referrals[j],
709                                                    ldb_dn_get_linearized(data->partitions[i]->ctrl->dn)) != NULL) {
710                                                 str_list_remove(ac->referrals,
711                                                                 ac->referrals[j]);
712                                         } else {
713                                                 ++j;
714                                         }
715                                 }
716
717                                 /* Add our new candidate */
718                                 ac->referrals = str_list_add(ac->referrals, ref);
719
720                                 talloc_free(ref);
721
722                                 if (ac->referrals == NULL) {
723                                         return ldb_oom(ldb);
724                                 }
725                         }
726                         if (ldb_dn_compare_base(data->partitions[i]->ctrl->dn, req->op.search.base) == 0) {
727                                 match = true;
728                                 stop = true; /* note that this relies on partition ordering */
729                         }
730                 }
731
732                 if (match) {
733                         ret = partition_prep_request(ac, data->partitions[i]);
734                         if (ret != LDB_SUCCESS) {
735                                 return ret;
736                         }
737                 }
738
739                 if (stop) break;
740         }
741
742         /* Perhaps we didn't match any partitions. Try the main partition */
743         if (ac->num_requests == 0) {
744                 talloc_free(ac);
745                 return ldb_next_request(module, req);
746         }
747
748         /* fire the first one */
749         return partition_call_first(ac);
750 }
751
752 /* add */
753 static int partition_add(struct ldb_module *module, struct ldb_request *req)
754 {
755         return partition_replicate(module, req, req->op.add.message->dn);
756 }
757
758 /* modify */
759 static int partition_modify(struct ldb_module *module, struct ldb_request *req)
760 {
761         return partition_replicate(module, req, req->op.mod.message->dn);
762 }
763
764 /* delete */
765 static int partition_delete(struct ldb_module *module, struct ldb_request *req)
766 {
767         return partition_replicate(module, req, req->op.del.dn);
768 }
769
770 /* rename */
771 static int partition_rename(struct ldb_module *module, struct ldb_request *req)
772 {
773         /* Find backend */
774         struct dsdb_partition *backend, *backend2;
775         
776         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
777                                                               struct partition_private_data);
778
779         /* Skip the lot if 'data' isn't here yet (initialisation) */
780         if (!data) {
781                 return ldb_operr(ldb_module_get_ctx(module));
782         }
783
784         backend = find_partition(data, req->op.rename.olddn, req);
785         backend2 = find_partition(data, req->op.rename.newdn, req);
786
787         if ((backend && !backend2) || (!backend && backend2)) {
788                 return LDB_ERR_AFFECTS_MULTIPLE_DSAS;
789         }
790
791         if (backend != backend2) {
792                 ldb_asprintf_errstring(ldb_module_get_ctx(module), 
793                                        "Cannot rename from %s in %s to %s in %s: %s",
794                                        ldb_dn_get_linearized(req->op.rename.olddn),
795                                        ldb_dn_get_linearized(backend->ctrl->dn),
796                                        ldb_dn_get_linearized(req->op.rename.newdn),
797                                        ldb_dn_get_linearized(backend2->ctrl->dn),
798                                        ldb_strerror(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
799                 return LDB_ERR_AFFECTS_MULTIPLE_DSAS;
800         }
801
802         return partition_replicate(module, req, req->op.rename.olddn);
803 }
804
805 /* start a transaction */
806 static int partition_start_trans(struct ldb_module *module)
807 {
808         int i;
809         int ret;
810         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
811                                                               struct partition_private_data);
812         /* Look at base DN */
813         /* Figure out which partition it is under */
814         /* Skip the lot if 'data' isn't here yet (initialization) */
815         if (ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING) {
816                 ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_start_trans() -> (metadata partition)");
817         }
818
819         /* This order must match that in prepare_commit() */
820         ret = ldb_next_start_trans(module);
821         if (ret != LDB_SUCCESS) {
822                 return ret;
823         }
824
825         ret = partition_reload_if_required(module, data, NULL);
826         if (ret != LDB_SUCCESS) {
827                 ldb_next_del_trans(module);
828                 return ret;
829         }
830
831         for (i=0; data && data->partitions && data->partitions[i]; i++) {
832                 if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
833                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_start_trans() -> %s",
834                                   ldb_dn_get_linearized(data->partitions[i]->ctrl->dn));
835                 }
836                 ret = ldb_next_start_trans(data->partitions[i]->module);
837                 if (ret != LDB_SUCCESS) {
838                         /* Back it out, if it fails on one */
839                         for (i--; i >= 0; i--) {
840                                 ldb_next_del_trans(data->partitions[i]->module);
841                         }
842                         ldb_next_del_trans(module);
843                         partition_metadata_del_trans(module);
844                         return ret;
845                 }
846         }
847
848         /*
849          * Because in prepare_commit this must come last, to ensure
850          * lock ordering we have to do this last here also 
851          */
852         ret = partition_metadata_start_trans(module);
853         if (ret != LDB_SUCCESS) {
854                 /* Back it out, if it fails on one */
855                 for (i--; i >= 0; i--) {
856                         ldb_next_del_trans(data->partitions[i]->module);
857                 }
858                 ldb_next_del_trans(module);
859                 return ret;
860         }
861
862         data->in_transaction++;
863
864         return LDB_SUCCESS;
865 }
866
867 /* prepare for a commit */
868 static int partition_prepare_commit(struct ldb_module *module)
869 {
870         unsigned int i;
871         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
872                                                               struct partition_private_data);
873         int ret;
874
875         ret = ldb_next_prepare_commit(module);
876         if (ret != LDB_SUCCESS) {
877                 return ret;
878         }
879
880         for (i=0; data && data->partitions && data->partitions[i]; i++) {
881                 if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
882                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_prepare_commit() -> %s",
883                                   ldb_dn_get_linearized(data->partitions[i]->ctrl->dn));
884                 }
885                 ret = ldb_next_prepare_commit(data->partitions[i]->module);
886                 if (ret != LDB_SUCCESS) {
887                         ldb_asprintf_errstring(ldb_module_get_ctx(module), "prepare_commit error on %s: %s",
888                                                ldb_dn_get_linearized(data->partitions[i]->ctrl->dn),
889                                                ldb_errstring(ldb_module_get_ctx(module)));
890                         return ret;
891                 }
892         }
893
894         if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
895                 ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_prepare_commit() -> (metadata partition)");
896         }
897
898         /* metadata prepare commit must come last, as other partitions could modify
899          * the database inside the prepare commit method of a module */
900         return partition_metadata_prepare_commit(module);
901 }
902
903
904 /* end a transaction */
905 static int partition_end_trans(struct ldb_module *module)
906 {
907         int ret, ret2;
908         unsigned int i;
909         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
910                                                               struct partition_private_data);
911
912         ret = LDB_SUCCESS;
913
914         if (data->in_transaction == 0) {
915                 DEBUG(0,("partition end transaction mismatch\n"));
916                 ret = LDB_ERR_OPERATIONS_ERROR;
917         } else {
918                 data->in_transaction--;
919         }
920
921         ret2 = partition_metadata_end_trans(module);
922         if (ret2 != LDB_SUCCESS) {
923                 ret = ret2;
924         }
925
926         for (i=0; data && data->partitions && data->partitions[i]; i++) {
927                 if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
928                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_end_trans() -> %s",
929                                   ldb_dn_get_linearized(data->partitions[i]->ctrl->dn));
930                 }
931                 ret2 = ldb_next_end_trans(data->partitions[i]->module);
932                 if (ret2 != LDB_SUCCESS) {
933                         ldb_asprintf_errstring(ldb_module_get_ctx(module), "end_trans error on %s: %s",
934                                                ldb_dn_get_linearized(data->partitions[i]->ctrl->dn),
935                                                ldb_errstring(ldb_module_get_ctx(module)));
936                         ret = ret2;
937                 }
938         }
939
940         if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
941                 ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_end_trans() -> (metadata partition)");
942         }
943         ret2 = ldb_next_end_trans(module);
944         if (ret2 != LDB_SUCCESS) {
945                 ret = ret2;
946         }
947         return ret;
948 }
949
950 /* delete a transaction */
951 static int partition_del_trans(struct ldb_module *module)
952 {
953         int ret, final_ret = LDB_SUCCESS;
954         unsigned int i;
955         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
956                                                               struct partition_private_data);
957         ret = partition_metadata_del_trans(module);
958         if (ret != LDB_SUCCESS) {
959                 final_ret = ret;
960         }
961
962         for (i=0; data && data->partitions && data->partitions[i]; i++) {
963                 if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
964                         ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_del_trans() -> %s",
965                                   ldb_dn_get_linearized(data->partitions[i]->ctrl->dn));
966                 }
967                 ret = ldb_next_del_trans(data->partitions[i]->module);
968                 if (ret != LDB_SUCCESS) {
969                         ldb_asprintf_errstring(ldb_module_get_ctx(module), "del_trans error on %s: %s",
970                                                ldb_dn_get_linearized(data->partitions[i]->ctrl->dn),
971                                                ldb_errstring(ldb_module_get_ctx(module)));
972                         final_ret = ret;
973                 }
974         }       
975
976         if (data->in_transaction == 0) {
977                 DEBUG(0,("partition del transaction mismatch\n"));
978                 return ldb_operr(ldb_module_get_ctx(module));
979         }
980         data->in_transaction--;
981
982         if ((module && ldb_module_flags(ldb_module_get_ctx(module)) & LDB_FLG_ENABLE_TRACING)) {
983                 ldb_debug(ldb_module_get_ctx(module), LDB_DEBUG_TRACE, "partition_del_trans() -> (metadata partition)");
984         }
985         ret = ldb_next_del_trans(module);
986         if (ret != LDB_SUCCESS) {
987                 final_ret = ret;
988         }
989         return final_ret;
990 }
991
992 int partition_primary_sequence_number(struct ldb_module *module, TALLOC_CTX *mem_ctx, 
993                                       uint64_t *seq_number,
994                                       struct ldb_request *parent)
995 {
996         int ret;
997         struct ldb_result *res;
998         struct ldb_seqnum_request *tseq;
999         struct ldb_seqnum_result *seqr;
1000
1001         tseq = talloc_zero(mem_ctx, struct ldb_seqnum_request);
1002         if (tseq == NULL) {
1003                 return ldb_oom(ldb_module_get_ctx(module));
1004         }
1005         tseq->type = LDB_SEQ_HIGHEST_SEQ;
1006         
1007         ret = dsdb_module_extended(module, tseq, &res,
1008                                    LDB_EXTENDED_SEQUENCE_NUMBER,
1009                                    tseq,
1010                                    DSDB_FLAG_NEXT_MODULE,
1011                                    parent);
1012         if (ret != LDB_SUCCESS) {
1013                 talloc_free(tseq);
1014                 return ret;
1015         }
1016         
1017         seqr = talloc_get_type_abort(res->extended->data,
1018                                      struct ldb_seqnum_result);
1019         if (seqr->flags & LDB_SEQ_TIMESTAMP_SEQUENCE) {
1020                 talloc_free(res);
1021                 return ldb_module_error(module, LDB_ERR_OPERATIONS_ERROR,
1022                         "Primary backend in partition module returned a timestamp based seq");
1023         }
1024
1025         *seq_number = seqr->seq_num;
1026         talloc_free(tseq);
1027         return LDB_SUCCESS;
1028 }
1029
1030
1031 /*
1032  * Older version of sequence number as sum of sequence numbers for each partition
1033  */
1034 int partition_sequence_number_from_partitions(struct ldb_module *module,
1035                                               uint64_t *seqr)
1036 {
1037         int ret;
1038         unsigned int i;
1039         uint64_t seq_number = 0;
1040         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
1041                                                               struct partition_private_data);
1042
1043         ret = partition_primary_sequence_number(module, data, &seq_number, NULL);
1044         if (ret != LDB_SUCCESS) {
1045                 return ret;
1046         }
1047         
1048         /* Skip the lot if 'data' isn't here yet (initialisation) */
1049         for (i=0; data && data->partitions && data->partitions[i]; i++) {
1050                 struct ldb_seqnum_request *tseq;
1051                 struct ldb_seqnum_result *tseqr;
1052                 struct ldb_request *treq;
1053                 struct ldb_result *res = talloc_zero(data, struct ldb_result);
1054                 if (res == NULL) {
1055                         return ldb_oom(ldb_module_get_ctx(module));
1056                 }
1057                 tseq = talloc_zero(res, struct ldb_seqnum_request);
1058                 if (tseq == NULL) {
1059                         talloc_free(res);
1060                         return ldb_oom(ldb_module_get_ctx(module));
1061                 }
1062                 tseq->type = LDB_SEQ_HIGHEST_SEQ;
1063                 
1064                 ret = ldb_build_extended_req(&treq, ldb_module_get_ctx(module), res,
1065                                              LDB_EXTENDED_SEQUENCE_NUMBER,
1066                                              tseq,
1067                                              NULL,
1068                                              res,
1069                                              ldb_extended_default_callback,
1070                                              NULL);
1071                 LDB_REQ_SET_LOCATION(treq);
1072                 if (ret != LDB_SUCCESS) {
1073                         talloc_free(res);
1074                         return ret;
1075                 }
1076                 
1077                 ret = partition_request(data->partitions[i]->module, treq);
1078                 if (ret != LDB_SUCCESS) {
1079                         talloc_free(res);
1080                         return ret;
1081                 }
1082                 ret = ldb_wait(treq->handle, LDB_WAIT_ALL);
1083                 if (ret != LDB_SUCCESS) {
1084                         talloc_free(res);
1085                         return ret;
1086                 }
1087                 tseqr = talloc_get_type(res->extended->data,
1088                                         struct ldb_seqnum_result);
1089                 seq_number += tseqr->seq_num;
1090                 talloc_free(res);
1091         }
1092
1093         *seqr = seq_number;
1094         return LDB_SUCCESS;
1095 }
1096
1097
1098 /*
1099  * Newer version of sequence number using metadata tdb
1100  */
1101 static int partition_sequence_number(struct ldb_module *module, struct ldb_request *req)
1102 {
1103         struct ldb_extended *ext;
1104         struct ldb_seqnum_request *seq;
1105         struct ldb_seqnum_result *seqr;
1106         uint64_t seq_number;
1107         int ret;
1108
1109         seq = talloc_get_type_abort(req->op.extended.data, struct ldb_seqnum_request);
1110         switch (seq->type) {
1111         case LDB_SEQ_NEXT:
1112                 ret = partition_metadata_sequence_number_increment(module, &seq_number);
1113                 if (ret != LDB_SUCCESS) {
1114                         return ret;
1115                 }
1116                 break;
1117
1118         case LDB_SEQ_HIGHEST_SEQ:
1119                 ret = partition_metadata_sequence_number(module, &seq_number);
1120                 if (ret != LDB_SUCCESS) {
1121                         return ret;
1122                 }
1123                 break;
1124
1125         case LDB_SEQ_HIGHEST_TIMESTAMP:
1126                 return ldb_module_error(module, LDB_ERR_OPERATIONS_ERROR,
1127                                         "LDB_SEQ_HIGHEST_TIMESTAMP not supported");
1128         }
1129
1130         ext = talloc_zero(req, struct ldb_extended);
1131         if (!ext) {
1132                 return ldb_module_oom(module);
1133         }
1134         seqr = talloc_zero(ext, struct ldb_seqnum_result);
1135         if (seqr == NULL) {
1136                 talloc_free(ext);
1137                 return ldb_module_oom(module);
1138         }
1139         ext->oid = LDB_EXTENDED_SEQUENCE_NUMBER;
1140         ext->data = seqr;
1141
1142         seqr->seq_num = seq_number;
1143         seqr->flags |= LDB_SEQ_GLOBAL_SEQUENCE;
1144
1145         /* send request done */
1146         return ldb_module_done(req, NULL, ext, LDB_SUCCESS);
1147 }
1148
1149 /* extended */
1150 static int partition_extended(struct ldb_module *module, struct ldb_request *req)
1151 {
1152         struct partition_private_data *data = talloc_get_type(ldb_module_get_private(module),
1153                                                               struct partition_private_data);
1154         struct partition_context *ac;
1155         int ret;
1156
1157         /* if we aren't initialised yet go further */
1158         if (!data) {
1159                 return ldb_next_request(module, req);
1160         }
1161
1162         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_SCHEMA_UPDATE_NOW_OID) == 0) {
1163                 /* Update the metadata.tdb to increment the schema version if needed*/
1164                 DEBUG(10, ("Incrementing the sequence_number after schema_update_now\n"));
1165                 ret = partition_metadata_inc_schema_sequence(module);
1166                 return ldb_module_done(req, NULL, NULL, ret);
1167         }
1168         
1169         if (strcmp(req->op.extended.oid, LDB_EXTENDED_SEQUENCE_NUMBER) == 0) {
1170                 return partition_sequence_number(module, req);
1171         }
1172
1173         if (strcmp(req->op.extended.oid, DSDB_EXTENDED_CREATE_PARTITION_OID) == 0) {
1174                 return partition_create(module, req);
1175         }
1176
1177         /* 
1178          * as the extended operation has no dn
1179          * we need to send it to all partitions
1180          */
1181
1182         ac = partition_init_ctx(module, req);
1183         if (!ac) {
1184                 return ldb_operr(ldb_module_get_ctx(module));
1185         }
1186
1187         return partition_send_all(module, ac, req);
1188 }
1189
1190 static const struct ldb_module_ops ldb_partition_module_ops = {
1191         .name              = "partition",
1192         .init_context      = partition_init,
1193         .search            = partition_search,
1194         .add               = partition_add,
1195         .modify            = partition_modify,
1196         .del               = partition_delete,
1197         .rename            = partition_rename,
1198         .extended          = partition_extended,
1199         .start_transaction = partition_start_trans,
1200         .prepare_commit    = partition_prepare_commit,
1201         .end_transaction   = partition_end_trans,
1202         .del_transaction   = partition_del_trans,
1203 };
1204
1205 int ldb_partition_module_init(const char *version)
1206 {
1207         LDB_MODULE_CHECK_VERSION(version);
1208         return ldb_register_module(&ldb_partition_module_ops);
1209 }