eb67cd3e309381e1141a0a7d630718f0d6a89dd6
[samba.git] / source4 / dsdb / samdb / ldb_modules / partition_init.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 #include "lib/util/tsort.h"
34 #include "lib/ldb-samba/ldb_wrap.h"
35 #include "system/filesys.h"
36
37 static int partition_sort_compare(const void *v1, const void *v2)
38 {
39         const struct dsdb_partition *p1;
40         const struct dsdb_partition *p2;
41
42         p1 = *((struct dsdb_partition * const*)v1);
43         p2 = *((struct dsdb_partition * const*)v2);
44
45         return ldb_dn_compare(p1->ctrl->dn, p2->ctrl->dn);
46 }
47
48 /* Load the list of DNs that we must replicate to all partitions */
49 static int partition_load_replicate_dns(struct ldb_context *ldb,
50                                         struct partition_private_data *data,
51                                         struct ldb_message *msg)
52 {
53         struct ldb_message_element *replicate_attributes = ldb_msg_find_element(msg, "replicateEntries");
54
55         talloc_free(data->replicate);
56         if (!replicate_attributes) {
57                 data->replicate = NULL;
58         } else {
59                 unsigned int i;
60                 data->replicate = talloc_array(data, struct ldb_dn *, replicate_attributes->num_values + 1);
61                 if (!data->replicate) {
62                         return ldb_oom(ldb);
63                 }
64
65                 for (i=0; i < replicate_attributes->num_values; i++) {
66                         data->replicate[i] = ldb_dn_from_ldb_val(data->replicate, ldb, &replicate_attributes->values[i]);
67                         if (!ldb_dn_validate(data->replicate[i])) {
68                                 ldb_asprintf_errstring(ldb,
69                                                         "partition_init: "
70                                                         "invalid DN in partition replicate record: %s", 
71                                                         replicate_attributes->values[i].data);
72                                 return LDB_ERR_CONSTRAINT_VIOLATION;
73                         }
74                 }
75                 data->replicate[i] = NULL;
76         }
77         return LDB_SUCCESS;
78 }
79
80 /* Load the list of modules for the partitions */
81 static int partition_load_modules(struct ldb_context *ldb, 
82                                   struct partition_private_data *data, struct ldb_message *msg) 
83 {
84         unsigned int i;
85         struct ldb_message_element *modules_attributes = ldb_msg_find_element(msg, "modules");
86         talloc_free(data->modules);
87         if (!modules_attributes) {
88                 return LDB_SUCCESS;
89         }
90         
91         data->modules = talloc_array(data, struct partition_module *, modules_attributes->num_values + 1);
92         if (!data->modules) {
93                 return ldb_oom(ldb);
94         }
95         
96         for (i=0; i < modules_attributes->num_values; i++) {
97                 char *p;
98                 DATA_BLOB dn_blob;
99                 data->modules[i] = talloc(data->modules, struct partition_module);
100                 if (!data->modules[i]) {
101                         return ldb_oom(ldb);
102                 }
103
104                 dn_blob = modules_attributes->values[i];
105
106                 p = strchr((const char *)dn_blob.data, ':');
107                 if (!p) {
108                         ldb_asprintf_errstring(ldb, 
109                                                "partition_load_modules: "
110                                                "invalid form for partition module record (missing ':'): %s", (const char *)dn_blob.data);
111                         return LDB_ERR_CONSTRAINT_VIOLATION;
112                 }
113                 /* Now trim off the filename */
114                 dn_blob.length = ((uint8_t *)p - dn_blob.data);
115
116                 p++;
117                 data->modules[i]->modules = ldb_modules_list_from_string(ldb, data->modules[i],
118                                                                          p);
119                 
120                 if (dn_blob.length == 1 && dn_blob.data[0] == '*') {
121                         data->modules[i]->dn = NULL;
122                 } else {
123                         data->modules[i]->dn = ldb_dn_from_ldb_val(data->modules[i], ldb, &dn_blob);
124                         if (!data->modules[i]->dn || !ldb_dn_validate(data->modules[i]->dn)) {
125                                 return ldb_operr(ldb);
126                         }
127                 }
128         }
129         data->modules[i] = NULL;
130         return LDB_SUCCESS;
131 }
132
133 static int partition_reload_metadata(struct ldb_module *module, struct partition_private_data *data, TALLOC_CTX *mem_ctx, struct ldb_message **_msg) 
134 {
135         int ret;
136         struct ldb_message *msg, *module_msg;
137         struct ldb_result *res;
138         struct ldb_context *ldb = ldb_module_get_ctx(module);
139         const char *attrs[] = { "partition", "replicateEntries", "modules", "ldapBackend", NULL };
140         /* perform search for @PARTITION, looking for module, replicateEntries and ldapBackend */
141         ret = dsdb_module_search_dn(module, mem_ctx, &res, 
142                                     ldb_dn_new(mem_ctx, ldb, DSDB_PARTITION_DN),
143                                     attrs,
144                                     DSDB_FLAG_NEXT_MODULE);
145         if (ret != LDB_SUCCESS) {
146                 return ret;
147         }
148
149         msg = res->msgs[0];
150
151         ret = partition_load_replicate_dns(ldb, data, msg);
152         if (ret != LDB_SUCCESS) {
153                 return ret;
154         }
155
156         /* When used from Samba4, this message is set by the samba4
157          * module, as a fixed value not read from the DB.  This avoids
158          * listing modules in the DB */
159         if (data->forced_module_msg) {
160                 module_msg = data->forced_module_msg;
161         } else {
162                 module_msg = msg;
163         }
164
165         ret = partition_load_modules(ldb, data, module_msg);
166         if (ret != LDB_SUCCESS) {
167                 return ret;
168         }
169
170         data->ldapBackend = talloc_steal(data, ldb_msg_find_attr_as_string(msg, "ldapBackend", NULL));
171         if (_msg) {
172                 *_msg = msg;
173         } else {
174                 talloc_free(msg);
175         }
176
177         return LDB_SUCCESS;
178 }
179
180 static const char **find_modules_for_dn(struct partition_private_data *data, struct ldb_dn *dn) 
181 {
182         unsigned int i;
183         struct partition_module *default_mod = NULL;
184         for (i=0; data->modules && data->modules[i]; i++) {
185                 if (!data->modules[i]->dn) {
186                         default_mod = data->modules[i];
187                 } else if (ldb_dn_compare(dn, data->modules[i]->dn) == 0) {
188                         return data->modules[i]->modules;
189                 }
190         }
191         if (default_mod) {
192                 return default_mod->modules;
193         } else {
194                 return NULL;
195         }
196 }
197
198 static int new_partition_from_dn(struct ldb_context *ldb, struct partition_private_data *data, 
199                                  TALLOC_CTX *mem_ctx, 
200                                  struct ldb_dn *dn, const char *filename,
201                                  struct dsdb_partition **partition) {
202         const char *backend_url;
203         struct dsdb_control_current_partition *ctrl;
204         struct ldb_module *backend_module;
205         struct ldb_module *module_chain;
206         const char **modules;
207         int ret;
208
209         (*partition) = talloc(mem_ctx, struct dsdb_partition);
210         if (!*partition) {
211                 return ldb_oom(ldb);
212         }
213
214         (*partition)->ctrl = ctrl = talloc((*partition), struct dsdb_control_current_partition);
215         if (!ctrl) {
216                 talloc_free(*partition);
217                 return ldb_oom(ldb);
218         }
219
220         /* See if an LDAP backend has been specified */
221         if (data->ldapBackend) {
222                 (*partition)->backend_url = data->ldapBackend;
223         } else {
224                 /* the backend LDB is the DN (base64 encoded if not 'plain') followed by .ldb */
225                 backend_url = ldb_relative_path(ldb, 
226                                                   *partition, 
227                                                   filename);
228                 if (!backend_url) {
229                         ldb_asprintf_errstring(ldb, 
230                                                "partition_init: unable to determine an relative path for partition: %s", filename);
231                         talloc_free(*partition);
232                         return LDB_ERR_OPERATIONS_ERROR;
233                 }
234                 (*partition)->backend_url = talloc_steal((*partition), backend_url);
235
236                 if (!(ldb_module_flags(ldb) & LDB_FLG_RDONLY)) {
237                         char *p;
238                         char *backend_dir = talloc_strdup(*partition, backend_url);
239                         
240                         p = strrchr(backend_dir, '/');
241                         if (p) {
242                                 p[0] = '\0';
243                         }
244
245                         /* Failure is quite reasonable, it might alredy exist */
246                         mkdir(backend_dir, 0700);
247                         talloc_free(backend_dir);
248                 }
249
250         }
251
252         ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
253         ctrl->dn = talloc_steal(ctrl, dn);
254         
255         ret = ldb_module_connect_backend(ldb, (*partition)->backend_url, NULL, &backend_module);
256         if (ret != LDB_SUCCESS) {
257                 return ret;
258         }
259         talloc_steal((*partition), backend_module);
260
261         modules = find_modules_for_dn(data, dn);
262
263         if (!modules) {
264                 DEBUG(0, ("Unable to load partition modules for new DN %s, perhaps you need to reprovision?  See partition-upgrade.txt for instructions\n", ldb_dn_get_linearized(dn)));
265                 talloc_free(*partition);
266                 return LDB_ERR_CONSTRAINT_VIOLATION;
267         }
268         ret = ldb_module_load_list(ldb, modules, backend_module, &module_chain);
269         if (ret != LDB_SUCCESS) {
270                 ldb_asprintf_errstring(ldb, 
271                                        "partition_init: "
272                                        "loading backend for %s failed: %s", 
273                                        ldb_dn_get_linearized(dn), ldb_errstring(ldb));
274                 talloc_free(*partition);
275                 return ret;
276         }
277         ret = ldb_module_init_chain(ldb, module_chain);
278         if (ret != LDB_SUCCESS) {
279                 ldb_asprintf_errstring(ldb,
280                                        "partition_init: "
281                                        "initialising backend for %s failed: %s", 
282                                        ldb_dn_get_linearized(dn), ldb_errstring(ldb));
283                 talloc_free(*partition);
284                 return ret;
285         }
286
287         /* This weirdness allows us to use ldb_next_request() in partition.c */
288         (*partition)->module = ldb_module_new(*partition, ldb, "partition_next", NULL);
289         if (!(*partition)->module) {
290                 talloc_free(*partition);
291                 return ldb_oom(ldb);
292         }
293         ldb_module_set_next((*partition)->module, talloc_steal((*partition)->module, module_chain));
294
295         /* if we were in a transaction then we need to start a
296            transaction on this new partition, otherwise we'll get a
297            transaction mismatch when we end the transaction */
298         if (data->in_transaction) {
299                 if (ldb_module_flags(ldb) & LDB_FLG_ENABLE_TRACING) {
300                         ldb_debug(ldb, LDB_DEBUG_TRACE, "partition_start_trans() -> %s (new partition)", 
301                                   ldb_dn_get_linearized((*partition)->ctrl->dn));
302                 }
303                 ret = ldb_next_start_trans((*partition)->module);
304         }
305
306         return ret;
307 }
308
309 /* Tell the rootDSE about the new partition */
310 static int partition_register(struct ldb_context *ldb, struct dsdb_control_current_partition *ctrl) 
311 {
312         struct ldb_request *req;
313         int ret;
314
315         req = talloc_zero(NULL, struct ldb_request);
316         if (req == NULL) {
317                 return ldb_oom(ldb);
318         }
319                 
320         req->operation = LDB_REQ_REGISTER_PARTITION;
321         req->op.reg_partition.dn = ctrl->dn;
322         req->callback = ldb_op_default_callback;
323
324         ldb_set_timeout(ldb, req, 0);
325         
326         req->handle = ldb_handle_new(req, ldb);
327         if (req->handle == NULL) {
328                 talloc_free(req);
329                 return ldb_operr(ldb);
330         }
331         
332         ret = ldb_request(ldb, req);
333         if (ret == LDB_SUCCESS) {
334                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
335         }
336         if (ret != LDB_SUCCESS) {
337                 ldb_debug(ldb, LDB_DEBUG_ERROR, "partition: Unable to register partition with rootdse!\n");
338                 talloc_free(req);
339                 return LDB_ERR_OTHER;
340         }
341         talloc_free(req);
342
343         return LDB_SUCCESS;
344 }
345
346 /* Add a newly found partition to the global data */
347 static int add_partition_to_data(struct ldb_context *ldb, struct partition_private_data *data,
348                                  struct dsdb_partition *partition)
349 {
350         unsigned int i;
351         int ret;
352
353         /* Count the partitions */
354         for (i=0; data->partitions && data->partitions[i]; i++) { /* noop */};
355         
356         /* Add partition to list of partitions */
357         data->partitions = talloc_realloc(data, data->partitions, struct dsdb_partition *, i + 2);
358         if (!data->partitions) {
359                 return ldb_oom(ldb);
360         }
361         data->partitions[i] = talloc_steal(data->partitions, partition);
362         data->partitions[i+1] = NULL;
363         
364         /* Sort again (should use binary insert) */
365         TYPESAFE_QSORT(data->partitions, i+1, partition_sort_compare);
366         
367         ret = partition_register(ldb, partition->ctrl);
368         if (ret != LDB_SUCCESS) {
369                 return ret;
370         }
371         return LDB_SUCCESS;
372 }
373
374 int partition_reload_if_required(struct ldb_module *module, 
375                                  struct partition_private_data *data)
376 {
377         uint64_t seq;
378         int ret;
379         unsigned int i;
380         struct ldb_context *ldb = ldb_module_get_ctx(module);
381         struct ldb_message *msg;
382         struct ldb_message_element *partition_attributes;
383         TALLOC_CTX *mem_ctx;
384
385         if (!data) {
386                 /* Not initilised yet */
387                 return LDB_SUCCESS;
388         }
389
390         mem_ctx = talloc_new(data);
391         if (!mem_ctx) {
392                 return ldb_oom(ldb);
393         }
394
395         ret = partition_primary_sequence_number(module, mem_ctx, LDB_SEQ_HIGHEST_SEQ, &seq);
396         if (ret != LDB_SUCCESS) {
397                 talloc_free(mem_ctx);
398                 return ret;
399         }
400         if (seq == data->metadata_seq) {
401                 talloc_free(mem_ctx);
402                 return LDB_SUCCESS;
403         }
404
405         ret = partition_reload_metadata(module, data, mem_ctx, &msg);
406         if (ret != LDB_SUCCESS) {
407                 talloc_free(mem_ctx);
408                 return ret;
409         }
410
411         data->metadata_seq = seq;
412
413         partition_attributes = ldb_msg_find_element(msg, "partition");
414
415         for (i=0; partition_attributes && i < partition_attributes->num_values; i++) {
416                 unsigned int j;
417                 bool new_partition = true;
418                 const char *filename = NULL;
419                 DATA_BLOB dn_blob;
420                 struct ldb_dn *dn;
421                 struct dsdb_partition *partition;
422                 struct ldb_result *dn_res;
423                 const char *no_attrs[] = { NULL };
424
425                 for (j=0; data->partitions && data->partitions[j]; j++) {
426                         if (data_blob_cmp(&data->partitions[j]->orig_record, &partition_attributes->values[i]) == 0) {
427                                 new_partition = false;
428                                 break;
429                         }
430                 }
431                 if (new_partition == false) {
432                         continue;
433                 }
434
435                 dn_blob = partition_attributes->values[i];
436                 
437                 if (dn_blob.length > 4 && 
438                     (strncmp((const char *)&dn_blob.data[dn_blob.length-4], ".ldb", 4) == 0)) {
439
440                         /* Look for DN:filename.ldb */
441                         char *p = strrchr((const char *)dn_blob.data, ':');
442                         if (!p) {
443                                 ldb_asprintf_errstring(ldb, 
444                                                        "partition_init: invalid DN in attempting to parse partition record: %s", (const char *)dn_blob.data);
445                                 talloc_free(mem_ctx);
446                                 return LDB_ERR_CONSTRAINT_VIOLATION;
447                         }
448                         filename = p+1;
449                         
450                         /* Now trim off the filename */
451                         dn_blob.length = ((uint8_t *)p - dn_blob.data);
452                 }
453
454                 dn = ldb_dn_from_ldb_val(mem_ctx, ldb, &dn_blob);
455                 if (!dn) {
456                         ldb_asprintf_errstring(ldb, 
457                                                "partition_init: invalid DN in partition record: %s", (const char *)dn_blob.data);
458                         talloc_free(mem_ctx);
459                         return LDB_ERR_CONSTRAINT_VIOLATION;
460                 }
461                 
462                 /* Now do a slow check with the DN compare */
463                 for (j=0; data->partitions && data->partitions[j]; j++) {
464                         if (ldb_dn_compare(dn, data->partitions[j]->ctrl->dn) == 0) {
465                                 new_partition = false;
466                                 break;
467                         }
468                 }
469                 if (new_partition == false) {
470                         continue;
471                 }
472
473                 if (!filename) {
474                         char *base64_dn = NULL;
475                         const char *p;
476                         for (p = ldb_dn_get_linearized(dn); *p; p++) {
477                                 /* We have such a strict check because I don't want shell metacharacters in the file name, nor ../ */
478                                 if (!(isalnum(*p) || *p == ' ' || *p == '=' || *p == ',')) {
479                                         break;
480                                 }
481                         }
482                         if (*p) {
483                                 base64_dn = ldb_base64_encode(data, ldb_dn_get_linearized(dn), strlen(ldb_dn_get_linearized(dn)));
484                                 filename = talloc_asprintf(mem_ctx, "%s.ldb", base64_dn);
485                         } else {
486                                 filename = talloc_asprintf(mem_ctx, "%s.ldb", ldb_dn_get_linearized(dn));
487                         }
488                 }
489                         
490                 /* We call ldb_dn_get_linearized() because the DN in
491                  * partition_attributes is already casefolded
492                  * correctly.  We don't want to mess that up as the
493                  * schema isn't loaded yet */
494                 ret = new_partition_from_dn(ldb, data, data->partitions, dn, 
495                                             filename,
496                                             &partition);
497                 if (ret != LDB_SUCCESS) {
498                         talloc_free(mem_ctx);
499                         return ret;
500                 }
501
502                 talloc_steal(partition, partition_attributes->values[i].data);
503                 partition->orig_record = partition_attributes->values[i];
504
505                 /* Get the 'correct' case of the partition DNs from the database */
506                 ret = dsdb_module_search_dn(partition->module, data, &dn_res, 
507                                             dn, no_attrs,
508                                             DSDB_FLAG_NEXT_MODULE);
509                 if (ret == LDB_SUCCESS) {
510                         talloc_free(partition->ctrl->dn);
511                         partition->ctrl->dn = talloc_steal(partition->ctrl, dn_res->msgs[0]->dn);
512                         talloc_free(dn_res);
513                 } else if (ret != LDB_ERR_NO_SUCH_OBJECT) {
514                         ldb_asprintf_errstring(ldb,
515                                                "Failed to search for partition base %s in new partition at %s: %s", 
516                                                ldb_dn_get_linearized(dn), 
517                                                partition->backend_url, 
518                                                ldb_errstring(ldb));
519                         talloc_free(mem_ctx);
520                         return ret;
521                 }
522
523                 ret = add_partition_to_data(ldb, data, partition);
524                 if (ret != LDB_SUCCESS) {
525                         talloc_free(mem_ctx);
526                         return ret;
527                 }
528         }
529
530         talloc_free(mem_ctx);
531         return LDB_SUCCESS;
532 }
533
534 /* Copy the metadata (@OPTIONS etc) for the new partition into the partition */
535
536 static int new_partition_set_replicated_metadata(struct ldb_context *ldb, 
537                                                  struct ldb_module *module, struct ldb_request *last_req, 
538                                                  struct partition_private_data *data, 
539                                                  struct dsdb_partition *partition)
540 {
541         unsigned int i;
542         int ret;
543         /* for each replicate, copy from main partition.  If we get an error, we report it up the chain */
544         for (i=0; data->replicate && data->replicate[i]; i++) {
545                 struct ldb_result *replicate_res;
546                 struct ldb_request *add_req;
547                 ret = dsdb_module_search_dn(module, last_req, &replicate_res, 
548                                             data->replicate[i],
549                                             NULL,
550                                             DSDB_FLAG_NEXT_MODULE);
551                 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
552                         continue;
553                 }
554                 if (ret != LDB_SUCCESS) {
555                         ldb_asprintf_errstring(ldb,
556                                                "Failed to search for %s from " DSDB_PARTITION_DN 
557                                                " replicateEntries for new partition at %s on %s: %s", 
558                                                ldb_dn_get_linearized(data->replicate[i]), 
559                                                partition->backend_url,
560                                                ldb_dn_get_linearized(partition->ctrl->dn), 
561                                                ldb_errstring(ldb));
562                         return ret;
563                 }
564
565                 /* Build add request */
566                 ret = ldb_build_add_req(&add_req, ldb, replicate_res, 
567                                         replicate_res->msgs[0], NULL, NULL, 
568                                         ldb_op_default_callback, last_req);
569                 LDB_REQ_SET_LOCATION(add_req);
570                 last_req = add_req;
571                 if (ret != LDB_SUCCESS) {
572                         /* return directly, this is a very unlikely error */
573                         return ret;
574                 }
575                 /* do request */
576                 ret = ldb_next_request(partition->module, add_req);
577                 /* wait */
578                 if (ret == LDB_SUCCESS) {
579                         ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
580                 }
581                 
582                 switch (ret) {
583                 case LDB_SUCCESS:
584                         break;
585
586                 case LDB_ERR_ENTRY_ALREADY_EXISTS:
587                         /* Handle this case specially - if the
588                          * metadata already exists, replace it */
589                 {
590                         struct ldb_request *del_req;
591                         
592                         /* Don't leave a confusing string in the ldb_errstring() */
593                         ldb_reset_err_string(ldb);
594                         /* Build del request */
595                         ret = ldb_build_del_req(&del_req, ldb, replicate_res, replicate_res->msgs[0]->dn, NULL, NULL, 
596                                                 ldb_op_default_callback, last_req);
597                         LDB_REQ_SET_LOCATION(del_req);
598                         last_req = del_req;
599                         if (ret != LDB_SUCCESS) {
600                                 /* return directly, this is a very unlikely error */
601                                 return ret;
602                         }
603                         /* do request */
604                         ret = ldb_next_request(partition->module, del_req);
605                         
606                         /* wait */
607                         if (ret == LDB_SUCCESS) {
608                                 ret = ldb_wait(del_req->handle, LDB_WAIT_ALL);
609                         }
610                         if (ret != LDB_SUCCESS) {
611                                 ldb_asprintf_errstring(ldb,
612                                                        "Failed to delete  (for re-add) %s from " DSDB_PARTITION_DN 
613                                                        " replicateEntries in new partition at %s on %s: %s", 
614                                                        ldb_dn_get_linearized(data->replicate[i]), 
615                                                        partition->backend_url,
616                                                        ldb_dn_get_linearized(partition->ctrl->dn), 
617                                                        ldb_errstring(ldb));
618                                 return ret;
619                         }
620                         
621                         /* Build add request */
622                         ret = ldb_build_add_req(&add_req, ldb, replicate_res, replicate_res->msgs[0], NULL, NULL, 
623                                                 ldb_op_default_callback, last_req);
624                         LDB_REQ_SET_LOCATION(add_req);
625                         last_req = add_req;
626                         if (ret != LDB_SUCCESS) {
627                                 /* return directly, this is a very unlikely error */
628                                 return ret;
629                         }
630                         
631                         /* do the add again */
632                         ret = ldb_next_request(partition->module, add_req);
633                         
634                         /* wait */
635                         if (ret == LDB_SUCCESS) {
636                                 ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
637                         }
638
639                         if (ret != LDB_SUCCESS) {
640                                 ldb_asprintf_errstring(ldb,
641                                                        "Failed to add (after delete) %s from " DSDB_PARTITION_DN 
642                                                        " replicateEntries to new partition at %s on %s: %s", 
643                                                        ldb_dn_get_linearized(data->replicate[i]), 
644                                                        partition->backend_url,
645                                                        ldb_dn_get_linearized(partition->ctrl->dn), 
646                                                        ldb_errstring(ldb));
647                                 return ret;
648                         }
649                         break;
650                 }
651                 default: 
652                 {
653                         ldb_asprintf_errstring(ldb,
654                                                "Failed to add %s from " DSDB_PARTITION_DN 
655                                                " replicateEntries to new partition at %s on %s: %s", 
656                                                ldb_dn_get_linearized(data->replicate[i]), 
657                                                partition->backend_url,
658                                                ldb_dn_get_linearized(partition->ctrl->dn), 
659                                                ldb_errstring(ldb));
660                         return ret;
661                 }
662                 }
663
664                 /* And around again, for the next thing we must merge */
665         }
666         return LDB_SUCCESS;
667 }
668
669 /* Extended operation to create a new partition, called when
670  * 'new_partition' detects that one is being added based on it's
671  * instanceType */
672 int partition_create(struct ldb_module *module, struct ldb_request *req)
673 {
674         unsigned int i;
675         int ret;
676         struct ldb_context *ldb = ldb_module_get_ctx(module);
677         struct ldb_request *mod_req, *last_req = req;
678         struct ldb_message *mod_msg;
679         struct partition_private_data *data;
680         struct dsdb_partition *partition = NULL;
681         const char *casefold_dn;
682         bool new_partition = false;
683
684         /* Check if this is already a partition */
685
686         struct dsdb_create_partition_exop *ex_op = talloc_get_type(req->op.extended.data, struct dsdb_create_partition_exop);
687         struct ldb_dn *dn = ex_op->new_dn;
688
689         data = talloc_get_type(ldb_module_get_private(module), struct partition_private_data);
690         if (!data) {
691                 /* We are not going to create a partition before we are even set up */
692                 return LDB_ERR_UNWILLING_TO_PERFORM;
693         }
694
695         for (i=0; data->partitions && data->partitions[i]; i++) {
696                 if (ldb_dn_compare(data->partitions[i]->ctrl->dn, dn) == 0) {
697                         partition = data->partitions[i];
698                 }
699         }
700
701         if (!partition) {
702                 char *filename;
703                 char *partition_record;
704                 new_partition = true;
705                 mod_msg = ldb_msg_new(req);
706                 if (!mod_msg) {
707                         return ldb_oom(ldb);
708                 }
709                 
710                 mod_msg->dn = ldb_dn_new(mod_msg, ldb, DSDB_PARTITION_DN);
711                 ret = ldb_msg_add_empty(mod_msg, DSDB_PARTITION_ATTR, LDB_FLAG_MOD_ADD, NULL);
712                 if (ret != LDB_SUCCESS) {
713                         return ret;
714                 }
715                 
716                 casefold_dn = ldb_dn_get_casefold(dn);
717                 
718                 {
719                         char *escaped;
720                         const char *p, *sam_name;
721                         sam_name = strrchr((const char *)ldb_get_opaque(ldb, "ldb_url"), '/');
722                         if (!sam_name) {
723                                 return ldb_operr(ldb);
724                         }
725                         sam_name++;
726
727                         for (p = casefold_dn; *p; p++) {
728                                 /* We have such a strict check because
729                                  * I don't want shell metacharacters
730                                  * in the file name, nor ../, but I do
731                                  * want it to be easily typed if SAFE
732                                  * to do so */
733                                 if (!(isalnum(*p) || *p == ' ' || *p == '=' || *p == ',')) {
734                                         break;
735                                 }
736                         }
737                         if (*p) {
738                                 escaped = rfc1738_escape_part(mod_msg, casefold_dn);
739                                 if (!escaped) {
740                                         return ldb_oom(ldb);
741                                 }
742                                 filename = talloc_asprintf(mod_msg, "%s.d/%s.ldb", sam_name, escaped);
743                                 talloc_free(escaped);
744                         } else {
745                                 filename = talloc_asprintf(mod_msg, "%s.d/%s.ldb", sam_name, casefold_dn);
746                         }
747
748                         if (!filename) {
749                                 return ldb_oom(ldb);
750                         }
751                 }
752                 partition_record = talloc_asprintf(mod_msg, "%s:%s", casefold_dn, filename);
753
754                 ret = ldb_msg_add_steal_string(mod_msg, DSDB_PARTITION_ATTR, partition_record);
755                 if (ret != LDB_SUCCESS) {
756                         return ret;
757                 }
758                 
759                 /* Perform modify on @PARTITION record */
760                 ret = ldb_build_mod_req(&mod_req, ldb, req, mod_msg, NULL, NULL, 
761                                         ldb_op_default_callback, req);
762                 LDB_REQ_SET_LOCATION(mod_req);
763                 if (ret != LDB_SUCCESS) {
764                         return ret;
765                 }
766                 
767                 last_req = mod_req;
768
769                 ret = ldb_next_request(module, mod_req);
770                 if (ret == LDB_SUCCESS) {
771                         ret = ldb_wait(mod_req->handle, LDB_WAIT_ALL);
772                 }
773                 
774                 if (ret != LDB_SUCCESS) {
775                         return ret;
776                 }
777                 
778                 /* Make a partition structure for this new partition, so we can copy in the template structure */ 
779                 ret = new_partition_from_dn(ldb, data, req, ldb_dn_copy(req, dn), filename, &partition);
780                 if (ret != LDB_SUCCESS) {
781                         return ret;
782                 }
783                 talloc_steal(partition, partition_record);
784                 partition->orig_record = data_blob_string_const(partition_record);
785         }
786         
787         ret = new_partition_set_replicated_metadata(ldb, module, last_req, data, partition);
788         if (ret != LDB_SUCCESS) {
789                 return ret;
790         }
791         
792         if (new_partition) {
793                 ret = add_partition_to_data(ldb, data, partition);
794                 if (ret != LDB_SUCCESS) {
795                         return ret;
796                 }
797         }
798
799         /* send request done */
800         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
801 }
802
803
804 int partition_init(struct ldb_module *module)
805 {
806         int ret;
807         TALLOC_CTX *mem_ctx = talloc_new(module);
808         struct ldb_context *ldb = ldb_module_get_ctx(module);
809         struct partition_private_data *data;
810
811         if (!mem_ctx) {
812                 return ldb_operr(ldb);
813         }
814
815         data = talloc_zero(mem_ctx, struct partition_private_data);
816         if (data == NULL) {
817                 return ldb_operr(ldb);
818         }
819
820         /* When used from Samba4, this message is set by the samba4
821          * module, as a fixed value not read from the DB.  This avoids
822          * listing modules in the DB */
823         data->forced_module_msg = talloc_get_type(
824                 ldb_get_opaque(ldb,
825                                DSDB_OPAQUE_PARTITION_MODULE_MSG_OPAQUE_NAME),
826                 struct ldb_message);
827
828         /* This loads the partitions */
829         ret = partition_reload_if_required(module, data);
830         if (ret != LDB_SUCCESS) {
831                 return ret;
832         }
833
834         ldb_module_set_private(module, talloc_steal(module, data));
835         talloc_free(mem_ctx);
836
837         ret = ldb_mod_register_control(module, LDB_CONTROL_DOMAIN_SCOPE_OID);
838         if (ret != LDB_SUCCESS) {
839                 ldb_debug(ldb, LDB_DEBUG_ERROR,
840                         "partition: Unable to register control with rootdse!\n");
841                 return ldb_operr(ldb);
842         }
843
844         ret = ldb_mod_register_control(module, LDB_CONTROL_SEARCH_OPTIONS_OID);
845         if (ret != LDB_SUCCESS) {
846                 ldb_debug(ldb, LDB_DEBUG_ERROR,
847                         "partition: Unable to register control with rootdse!\n");
848                 return ldb_operr(ldb);
849         }
850
851         return ldb_next_init(module);
852 }