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