]> git.sur5r.net Git - openldap/blob - servers/slapd/bconfig.c
Fix schema undo crash
[openldap] / servers / slapd / bconfig.c
1 /* bconfig.c - the config backend */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2005-2007 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was originally developed by Howard Chu for inclusion
18  * in OpenLDAP Software.
19  */
20
21 #include "portable.h"
22
23 #include <stdio.h>
24 #include <ac/string.h>
25 #include <ac/ctype.h>
26 #include <ac/errno.h>
27 #include <sys/stat.h>
28
29 #include "slap.h"
30
31 #ifdef LDAP_SLAPI
32 #include "slapi/slapi.h"
33 #endif
34
35 #include <ldif.h>
36 #include <lutil.h>
37
38 #include "config.h"
39
40 #define CONFIG_RDN      "cn=config"
41 #define SCHEMA_RDN      "cn=schema"
42
43 static struct berval config_rdn = BER_BVC(CONFIG_RDN);
44 static struct berval schema_rdn = BER_BVC(SCHEMA_RDN);
45
46 extern int slap_DN_strict;      /* dn.c */
47
48 #ifdef SLAPD_MODULES
49 typedef struct modpath_s {
50         struct modpath_s *mp_next;
51         struct berval mp_path;
52         BerVarray mp_loads;
53 } ModPaths;
54
55 static ModPaths modpaths, *modlast = &modpaths, *modcur = &modpaths;
56 #endif
57
58 typedef struct ConfigFile {
59         struct ConfigFile *c_sibs;
60         struct ConfigFile *c_kids;
61         struct berval c_file;
62         AttributeType *c_at_head, *c_at_tail;
63         ContentRule *c_cr_head, *c_cr_tail;
64         ObjectClass *c_oc_head, *c_oc_tail;
65         OidMacro *c_om_head, *c_om_tail;
66         BerVarray c_dseFiles;
67 } ConfigFile;
68
69 typedef struct {
70         ConfigFile *cb_config;
71         CfEntryInfo *cb_root;
72         BackendDB       cb_db;  /* underlying database */
73         int             cb_got_ldif;
74         int             cb_use_ldif;
75 } CfBackInfo;
76
77 static CfBackInfo cfBackInfo;
78
79 static char     *passwd_salt;
80 static char     *logfileName;
81 #ifdef SLAP_AUTH_REWRITE
82 static BerVarray authz_rewrites;
83 #endif
84
85 static struct berval cfdir;
86
87 /* Private state */
88 static AttributeDescription *cfAd_backend, *cfAd_database, *cfAd_overlay,
89         *cfAd_include, *cfAd_attr, *cfAd_oc, *cfAd_om;
90
91 static ConfigFile *cfn;
92
93 static Avlnode *CfOcTree;
94
95 /* System schema state */
96 extern AttributeType *at_sys_tail;      /* at.c */
97 extern ObjectClass *oc_sys_tail;        /* oc.c */
98 extern OidMacro *om_sys_tail;   /* oidm.c */
99 static AttributeType *cf_at_tail;
100 static ObjectClass *cf_oc_tail;
101 static OidMacro *cf_om_tail;
102
103 static int config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca,
104         SlapReply *rs, int *renumber, Operation *op );
105
106 static int config_check_schema( Operation *op, CfBackInfo *cfb );
107
108 static ConfigDriver config_fname;
109 static ConfigDriver config_cfdir;
110 static ConfigDriver config_generic;
111 static ConfigDriver config_search_base;
112 static ConfigDriver config_passwd_hash;
113 static ConfigDriver config_schema_dn;
114 static ConfigDriver config_sizelimit;
115 static ConfigDriver config_timelimit;
116 static ConfigDriver config_overlay;
117 static ConfigDriver config_subordinate; 
118 static ConfigDriver config_suffix; 
119 static ConfigDriver config_rootdn;
120 static ConfigDriver config_rootpw;
121 static ConfigDriver config_restrict;
122 static ConfigDriver config_allows;
123 static ConfigDriver config_disallows;
124 static ConfigDriver config_requires;
125 static ConfigDriver config_security;
126 static ConfigDriver config_referral;
127 static ConfigDriver config_loglevel;
128 static ConfigDriver config_updatedn;
129 static ConfigDriver config_updateref;
130 static ConfigDriver config_include;
131 static ConfigDriver config_obsolete;
132 #ifdef HAVE_TLS
133 static ConfigDriver config_tls_option;
134 static ConfigDriver config_tls_config;
135 #endif
136 extern ConfigDriver syncrepl_config;
137
138 enum {
139         CFG_ACL = 1,
140         CFG_BACKEND,
141         CFG_DATABASE,
142         CFG_TLS_RAND,
143         CFG_TLS_CIPHER,
144         CFG_TLS_CERT_FILE,
145         CFG_TLS_CERT_KEY,
146         CFG_TLS_CA_PATH,
147         CFG_TLS_CA_FILE,
148         CFG_TLS_DH_FILE,
149         CFG_TLS_VERIFY,
150         CFG_TLS_CRLCHECK,
151         CFG_TLS_CRL_FILE,
152         CFG_CONCUR,
153         CFG_THREADS,
154         CFG_SALT,
155         CFG_LIMITS,
156         CFG_RO,
157         CFG_REWRITE,
158         CFG_DEPTH,
159         CFG_OID,
160         CFG_OC,
161         CFG_DIT,
162         CFG_ATTR,
163         CFG_ATOPT,
164         CFG_ROOTDSE,
165         CFG_LOGFILE,
166         CFG_PLUGIN,
167         CFG_MODLOAD,
168         CFG_MODPATH,
169         CFG_LASTMOD,
170         CFG_AZPOLICY,
171         CFG_AZREGEXP,
172         CFG_SASLSECP,
173         CFG_SSTR_IF_MAX,
174         CFG_SSTR_IF_MIN,
175         CFG_TTHREADS,
176         CFG_MIRRORMODE,
177         CFG_HIDDEN,
178         CFG_MONITORING,
179         CFG_SERVERID,
180
181         CFG_LAST
182 };
183
184 typedef struct {
185         char *name, *oid;
186 } OidRec;
187
188 static OidRec OidMacros[] = {
189         /* OpenLDAProot:666.11.1 */
190         { "OLcfg", "1.3.6.1.4.1.4203.666.11.1" },
191         { "OLcfgAt", "OLcfg:3" },
192         { "OLcfgGlAt", "OLcfgAt:0" },
193         { "OLcfgBkAt", "OLcfgAt:1" },
194         { "OLcfgDbAt", "OLcfgAt:2" },
195         { "OLcfgOvAt", "OLcfgAt:3" },
196         { "OLcfgOc", "OLcfg:4" },
197         { "OLcfgGlOc", "OLcfgOc:0" },
198         { "OLcfgBkOc", "OLcfgOc:1" },
199         { "OLcfgDbOc", "OLcfgOc:2" },
200         { "OLcfgOvOc", "OLcfgOc:3" },
201
202         /* Syntaxes. We should just start using the standard names and
203          * document that they are predefined and available for users
204          * to reference in their own schema. Defining schema without
205          * OID macros is for masochists...
206          */
207         { "OMsyn", "1.3.6.1.4.1.1466.115.121.1" },
208         { "OMsBoolean", "OMsyn:7" },
209         { "OMsDN", "OMsyn:12" },
210         { "OMsDirectoryString", "OMsyn:15" },
211         { "OMsInteger", "OMsyn:27" },
212         { "OMsOID", "OMsyn:38" },
213         { "OMsOctetString", "OMsyn:40" },
214         { NULL, NULL }
215 };
216
217 /*
218  * Backend/Database registry
219  *
220  * OLcfg{Bk|Db}{Oc|At}:0                -> common
221  * OLcfg{Bk|Db}{Oc|At}:1                -> back-bdb(/back-hdb)
222  * OLcfg{Bk|Db}{Oc|At}:2                -> back-ldif
223  * OLcfg{Bk|Db}{Oc|At}:3                -> back-ldap
224  * OLcfg{Bk|Db}{Oc|At}:4                -> back-monitor
225  * OLcfg{Bk|Db}{Oc|At}:5                -> back-relay
226  * OLcfg{Bk|Db}{Oc|At}:6                -> back-sql
227  */
228
229 /*
230  * Overlay registry
231  *
232  * OLcfgOv{Oc|At}:1                     -> syncprov
233  * OLcfgOv{Oc|At}:2                     -> pcache
234  * OLcfgOv{Oc|At}:3                     -> chain
235  * OLcfgOv{Oc|At}:4                     -> accesslog
236  * OLcfgOv{Oc|At}:5                     -> valsort
237  * (FIXME: separate arc for contribware?)
238  * OLcfgOv{Oc|At}:6                     -> smbk5pwd
239  * OLcfgOv{Oc|At}:7                     -> distproc
240  * OLcfgOv{Oc|At}:8                     -> dynlist
241  * OLcfgOv{Oc|At}:9                     -> dds
242  * OLcfgOv{Oc|At}:10                    -> unique
243  * OLcfgOv{Oc|At}:11                    -> refint
244  * OLcfgOv{Oc|At}:12                    -> ppolicy
245  * OLcfgOv{Oc|At}:13                    -> constraint
246  * OLcfgOv{Oc|At}:14                    -> translucent
247  * OLcfgOv{Oc|At}:15                    -> auditlog
248  * OLcfgOv{Oc|At}:16                    -> rwm
249  * OLcfgOv{Oc|At}:17                    -> dyngroup
250  * OLcfgOv{Oc|At}:18                    -> memberof
251  * OLcfgOv{Oc|At}:19                    -> collect
252  */
253
254 /* alphabetical ordering */
255
256 static ConfigTable config_back_cf_table[] = {
257         /* This attr is read-only */
258         { "", "", 0, 0, 0, ARG_MAGIC,
259                 &config_fname, "( OLcfgGlAt:78 NAME 'olcConfigFile' "
260                         "DESC 'File for slapd configuration directives' "
261                         "EQUALITY caseIgnoreMatch "
262                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
263         { "", "", 0, 0, 0, ARG_MAGIC,
264                 &config_cfdir, "( OLcfgGlAt:79 NAME 'olcConfigDir' "
265                         "DESC 'Directory for slapd configuration backend' "
266                         "EQUALITY caseIgnoreMatch "
267                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
268         { "access",     NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC|CFG_ACL,
269                 &config_generic, "( OLcfgGlAt:1 NAME 'olcAccess' "
270                         "DESC 'Access Control List' "
271                         "EQUALITY caseIgnoreMatch "
272                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
273         { "allows",     "features", 2, 0, 5, ARG_PRE_DB|ARG_MAGIC,
274                 &config_allows, "( OLcfgGlAt:2 NAME 'olcAllows' "
275                         "DESC 'Allowed set of deprecated features' "
276                         "EQUALITY caseIgnoreMatch "
277                         "SYNTAX OMsDirectoryString )", NULL, NULL },
278         { "argsfile", "file", 2, 2, 0, ARG_STRING,
279                 &slapd_args_file, "( OLcfgGlAt:3 NAME 'olcArgsFile' "
280                         "DESC 'File for slapd command line options' "
281                         "EQUALITY caseIgnoreMatch "
282                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
283         { "attributeoptions", NULL, 0, 0, 0, ARG_MAGIC|CFG_ATOPT,
284                 &config_generic, "( OLcfgGlAt:5 NAME 'olcAttributeOptions' "
285                         "EQUALITY caseIgnoreMatch "
286                         "SYNTAX OMsDirectoryString )", NULL, NULL },
287         { "attribute",  "attribute", 2, 0, STRLENOF( "attribute" ),
288                 ARG_PAREN|ARG_MAGIC|CFG_ATTR,
289                 &config_generic, "( OLcfgGlAt:4 NAME 'olcAttributeTypes' "
290                         "DESC 'OpenLDAP attributeTypes' "
291                         "EQUALITY caseIgnoreMatch "
292                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
293                                 NULL, NULL },
294         { "authid-rewrite", NULL, 2, 0, STRLENOF( "authid-rewrite" ),
295 #ifdef SLAP_AUTH_REWRITE
296                 ARG_MAGIC|CFG_REWRITE|ARG_NO_INSERT, &config_generic,
297 #else
298                 ARG_IGNORED, NULL,
299 #endif
300                  "( OLcfgGlAt:6 NAME 'olcAuthIDRewrite' "
301                         "EQUALITY caseIgnoreMatch "
302                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
303         { "authz-policy", "policy", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_AZPOLICY,
304                 &config_generic, "( OLcfgGlAt:7 NAME 'olcAuthzPolicy' "
305                         "EQUALITY caseIgnoreMatch "
306                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
307         { "authz-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP|ARG_NO_INSERT,
308                 &config_generic, "( OLcfgGlAt:8 NAME 'olcAuthzRegexp' "
309                         "EQUALITY caseIgnoreMatch "
310                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
311         { "backend", "type", 2, 2, 0, ARG_PRE_DB|ARG_MAGIC|CFG_BACKEND,
312                 &config_generic, "( OLcfgGlAt:9 NAME 'olcBackend' "
313                         "DESC 'A type of backend' "
314                         "EQUALITY caseIgnoreMatch "
315                         "SYNTAX OMsDirectoryString SINGLE-VALUE X-ORDERED 'SIBLINGS' )",
316                                 NULL, NULL },
317         { "concurrency", "level", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_CONCUR,
318                 &config_generic, "( OLcfgGlAt:10 NAME 'olcConcurrency' "
319                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
320         { "conn_max_pending", "max", 2, 2, 0, ARG_INT,
321                 &slap_conn_max_pending, "( OLcfgGlAt:11 NAME 'olcConnMaxPending' "
322                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
323         { "conn_max_pending_auth", "max", 2, 2, 0, ARG_INT,
324                 &slap_conn_max_pending_auth, "( OLcfgGlAt:12 NAME 'olcConnMaxPendingAuth' "
325                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
326         { "database", "type", 2, 2, 0, ARG_MAGIC|CFG_DATABASE,
327                 &config_generic, "( OLcfgGlAt:13 NAME 'olcDatabase' "
328                         "DESC 'The backend type for a database instance' "
329                         "SUP olcBackend SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
330         { "defaultSearchBase", "dn", 2, 2, 0, ARG_PRE_BI|ARG_PRE_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
331                 &config_search_base, "( OLcfgGlAt:14 NAME 'olcDefaultSearchBase' "
332                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
333         { "disallows", "features", 2, 0, 8, ARG_PRE_DB|ARG_MAGIC,
334                 &config_disallows, "( OLcfgGlAt:15 NAME 'olcDisallows' "
335                         "EQUALITY caseIgnoreMatch "
336                         "SYNTAX OMsDirectoryString )", NULL, NULL },
337         { "ditcontentrule",     NULL, 0, 0, 0, ARG_MAGIC|CFG_DIT|ARG_NO_DELETE|ARG_NO_INSERT,
338                 &config_generic, "( OLcfgGlAt:16 NAME 'olcDitContentRules' "
339                         "DESC 'OpenLDAP DIT content rules' "
340                         "EQUALITY caseIgnoreMatch "
341                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
342                         NULL, NULL },
343         { "gentlehup", "on|off", 2, 2, 0,
344 #ifdef SIGHUP
345                 ARG_ON_OFF, &global_gentlehup,
346 #else
347                 ARG_IGNORED, NULL,
348 #endif
349                 "( OLcfgGlAt:17 NAME 'olcGentleHUP' "
350                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
351         { "hidden", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_HIDDEN,
352                 &config_generic, "( OLcfgDbAt:0.17 NAME 'olcHidden' "
353                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
354         { "idletimeout", "timeout", 2, 2, 0, ARG_INT,
355                 &global_idletimeout, "( OLcfgGlAt:18 NAME 'olcIdleTimeout' "
356                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
357         { "include", "file", 2, 2, 0, ARG_MAGIC,
358                 &config_include, "( OLcfgGlAt:19 NAME 'olcInclude' "
359                         "SUP labeledURI )", NULL, NULL },
360         { "index_substr_if_minlen", "min", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MIN,
361                 &config_generic, "( OLcfgGlAt:20 NAME 'olcIndexSubstrIfMinLen' "
362                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
363         { "index_substr_if_maxlen", "max", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MAX,
364                 &config_generic, "( OLcfgGlAt:21 NAME 'olcIndexSubstrIfMaxLen' "
365                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
366         { "index_substr_any_len", "len", 2, 2, 0, ARG_INT|ARG_NONZERO,
367                 &index_substr_any_len, "( OLcfgGlAt:22 NAME 'olcIndexSubstrAnyLen' "
368                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
369         { "index_substr_any_step", "step", 2, 2, 0, ARG_INT|ARG_NONZERO,
370                 &index_substr_any_step, "( OLcfgGlAt:23 NAME 'olcIndexSubstrAnyStep' "
371                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
372         { "lastmod", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_LASTMOD,
373                 &config_generic, "( OLcfgDbAt:0.4 NAME 'olcLastMod' "
374                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
375         { "limits", "limits", 2, 0, 0, ARG_DB|ARG_MAGIC|CFG_LIMITS,
376                 &config_generic, "( OLcfgDbAt:0.5 NAME 'olcLimits' "
377                         "EQUALITY caseIgnoreMatch "
378                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
379         { "localSSF", "ssf", 2, 2, 0, ARG_INT,
380                 &local_ssf, "( OLcfgGlAt:26 NAME 'olcLocalSSF' "
381                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
382         { "logfile", "file", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_LOGFILE,
383                 &config_generic, "( OLcfgGlAt:27 NAME 'olcLogFile' "
384                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
385         { "loglevel", "level", 2, 0, 0, ARG_MAGIC,
386                 &config_loglevel, "( OLcfgGlAt:28 NAME 'olcLogLevel' "
387                         "EQUALITY caseIgnoreMatch "
388                         "SYNTAX OMsDirectoryString )", NULL, NULL },
389         { "maxDerefDepth", "depth", 2, 2, 0, ARG_DB|ARG_INT|ARG_MAGIC|CFG_DEPTH,
390                 &config_generic, "( OLcfgDbAt:0.6 NAME 'olcMaxDerefDepth' "
391                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
392         { "mirrormode", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_MIRRORMODE,
393                 &config_generic, "( OLcfgDbAt:0.16 NAME 'olcMirrorMode' "
394                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
395         { "moduleload", "file", 2, 0, 0,
396 #ifdef SLAPD_MODULES
397                 ARG_MAGIC|CFG_MODLOAD|ARG_NO_DELETE, &config_generic,
398 #else
399                 ARG_IGNORED, NULL,
400 #endif
401                 "( OLcfgGlAt:30 NAME 'olcModuleLoad' "
402                         "EQUALITY caseIgnoreMatch "
403                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
404         { "modulepath", "path", 2, 2, 0,
405 #ifdef SLAPD_MODULES
406                 ARG_MAGIC|CFG_MODPATH|ARG_NO_DELETE|ARG_NO_INSERT, &config_generic,
407 #else
408                 ARG_IGNORED, NULL,
409 #endif
410                 "( OLcfgGlAt:31 NAME 'olcModulePath' "
411                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
412         { "monitoring", "TRUE|FALSE", 2, 2, 0,
413                 ARG_MAGIC|CFG_MONITORING|ARG_DB|ARG_ON_OFF, &config_generic,
414                 "( OLcfgDbAt:0.18 NAME 'olcMonitoring' "
415                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
416         { "objectclass", "objectclass", 2, 0, 0, ARG_PAREN|ARG_MAGIC|CFG_OC,
417                 &config_generic, "( OLcfgGlAt:32 NAME 'olcObjectClasses' "
418                 "DESC 'OpenLDAP object classes' "
419                 "EQUALITY caseIgnoreMatch "
420                 "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
421                         NULL, NULL },
422         { "objectidentifier", "name> <oid",     3, 3, 0, ARG_MAGIC|CFG_OID,
423                 &config_generic, "( OLcfgGlAt:33 NAME 'olcObjectIdentifier' "
424                         "EQUALITY caseIgnoreMatch "
425                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
426         { "overlay", "overlay", 2, 2, 0, ARG_MAGIC,
427                 &config_overlay, "( OLcfgGlAt:34 NAME 'olcOverlay' "
428                         "SUP olcDatabase SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
429         { "password-crypt-salt-format", "salt", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_SALT,
430                 &config_generic, "( OLcfgGlAt:35 NAME 'olcPasswordCryptSaltFormat' "
431                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
432         { "password-hash", "hash", 2, 2, 0, ARG_MAGIC,
433                 &config_passwd_hash, "( OLcfgGlAt:36 NAME 'olcPasswordHash' "
434                         "EQUALITY caseIgnoreMatch "
435                         "SYNTAX OMsDirectoryString )", NULL, NULL },
436         { "pidfile", "file", 2, 2, 0, ARG_STRING,
437                 &slapd_pid_file, "( OLcfgGlAt:37 NAME 'olcPidFile' "
438                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
439         { "plugin", NULL, 0, 0, 0,
440 #ifdef LDAP_SLAPI
441                 ARG_MAGIC|CFG_PLUGIN, &config_generic,
442 #else
443                 ARG_IGNORED, NULL,
444 #endif
445                 "( OLcfgGlAt:38 NAME 'olcPlugin' "
446                         "EQUALITY caseIgnoreMatch "
447                         "SYNTAX OMsDirectoryString )", NULL, NULL },
448         { "pluginlog", "filename", 2, 2, 0,
449 #ifdef LDAP_SLAPI
450                 ARG_STRING, &slapi_log_file,
451 #else
452                 ARG_IGNORED, NULL,
453 #endif
454                 "( OLcfgGlAt:39 NAME 'olcPluginLogFile' "
455                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
456         { "readonly", "on|off", 2, 2, 0, ARG_MAY_DB|ARG_ON_OFF|ARG_MAGIC|CFG_RO,
457                 &config_generic, "( OLcfgGlAt:40 NAME 'olcReadOnly' "
458                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
459         { "referral", "url", 2, 2, 0, ARG_MAGIC,
460                 &config_referral, "( OLcfgGlAt:41 NAME 'olcReferral' "
461                         "SUP labeledURI SINGLE-VALUE )", NULL, NULL },
462         { "replica", "host or uri", 2, 0, 0, ARG_DB|ARG_MAGIC,
463                 &config_obsolete, "( OLcfgDbAt:0.7 NAME 'olcReplica' "
464                         "EQUALITY caseIgnoreMatch "
465                         "SUP labeledURI X-ORDERED 'VALUES' )", NULL, NULL },
466         { "replica-argsfile", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
467                 &config_obsolete, "( OLcfgGlAt:43 NAME 'olcReplicaArgsFile' "
468                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
469         { "replica-pidfile", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
470                 &config_obsolete, "( OLcfgGlAt:44 NAME 'olcReplicaPidFile' "
471                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
472         { "replicationInterval", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
473                 &config_obsolete, "( OLcfgGlAt:45 NAME 'olcReplicationInterval' "
474                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
475         { "replogfile", "filename", 2, 2, 0, ARG_MAY_DB|ARG_MAGIC,
476                 &config_obsolete, "( OLcfgGlAt:46 NAME 'olcReplogFile' "
477                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
478         { "require", "features", 2, 0, 7, ARG_MAY_DB|ARG_MAGIC,
479                 &config_requires, "( OLcfgGlAt:47 NAME 'olcRequires' "
480                         "EQUALITY caseIgnoreMatch "
481                         "SYNTAX OMsDirectoryString )", NULL, NULL },
482         { "restrict", "op_list", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
483                 &config_restrict, "( OLcfgGlAt:48 NAME 'olcRestrict' "
484                         "EQUALITY caseIgnoreMatch "
485                         "SYNTAX OMsDirectoryString )", NULL, NULL },
486         { "reverse-lookup", "on|off", 2, 2, 0,
487 #ifdef SLAPD_RLOOKUPS
488                 ARG_ON_OFF, &use_reverse_lookup,
489 #else
490                 ARG_IGNORED, NULL,
491 #endif
492                 "( OLcfgGlAt:49 NAME 'olcReverseLookup' "
493                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
494         { "rootdn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
495                 &config_rootdn, "( OLcfgDbAt:0.8 NAME 'olcRootDN' "
496                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
497         { "rootDSE", "file", 2, 2, 0, ARG_MAGIC|CFG_ROOTDSE,
498                 &config_generic, "( OLcfgGlAt:51 NAME 'olcRootDSE' "
499                         "EQUALITY caseIgnoreMatch "
500                         "SYNTAX OMsDirectoryString )", NULL, NULL },
501         { "rootpw", "password", 2, 2, 0, ARG_BERVAL|ARG_DB|ARG_MAGIC,
502                 &config_rootpw, "( OLcfgDbAt:0.9 NAME 'olcRootPW' "
503                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
504         { "sasl-authz-policy", NULL, 2, 2, 0, ARG_MAGIC|CFG_AZPOLICY,
505                 &config_generic, NULL, NULL, NULL },
506         { "sasl-host", "host", 2, 2, 0,
507 #ifdef HAVE_CYRUS_SASL
508                 ARG_STRING|ARG_UNIQUE, &global_host,
509 #else
510                 ARG_IGNORED, NULL,
511 #endif
512                 "( OLcfgGlAt:53 NAME 'olcSaslHost' "
513                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
514         { "sasl-realm", "realm", 2, 2, 0,
515 #ifdef HAVE_CYRUS_SASL
516                 ARG_STRING|ARG_UNIQUE, &global_realm,
517 #else
518                 ARG_IGNORED, NULL,
519 #endif
520                 "( OLcfgGlAt:54 NAME 'olcSaslRealm' "
521                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
522         { "sasl-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
523                 &config_generic, NULL, NULL, NULL },
524         { "sasl-secprops", "properties", 2, 2, 0,
525 #ifdef HAVE_CYRUS_SASL
526                 ARG_MAGIC|CFG_SASLSECP, &config_generic,
527 #else
528                 ARG_IGNORED, NULL,
529 #endif
530                 "( OLcfgGlAt:56 NAME 'olcSaslSecProps' "
531                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
532         { "saslRegexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
533                 &config_generic, NULL, NULL, NULL },
534         { "schemadn", "dn", 2, 2, 0, ARG_MAY_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
535                 &config_schema_dn, "( OLcfgGlAt:58 NAME 'olcSchemaDN' "
536                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
537         { "security", "factors", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
538                 &config_security, "( OLcfgGlAt:59 NAME 'olcSecurity' "
539                         "EQUALITY caseIgnoreMatch "
540                         "SYNTAX OMsDirectoryString )", NULL, NULL },
541         { "serverID", "number> <[URI]", 2, 3, 0, ARG_MAGIC|CFG_SERVERID,
542                 &config_generic, "( OLcfgGlAt:81 NAME 'olcServerID' "
543                         "EQUALITY caseIgnoreMatch "
544                         "SYNTAX OMsDirectoryString )", NULL, NULL },
545         { "sizelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
546                 &config_sizelimit, "( OLcfgGlAt:60 NAME 'olcSizeLimit' "
547                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
548         { "sockbuf_max_incoming", "max", 2, 2, 0, ARG_BER_LEN_T,
549                 &sockbuf_max_incoming, "( OLcfgGlAt:61 NAME 'olcSockbufMaxIncoming' "
550                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
551         { "sockbuf_max_incoming_auth", "max", 2, 2, 0, ARG_BER_LEN_T,
552                 &sockbuf_max_incoming_auth, "( OLcfgGlAt:62 NAME 'olcSockbufMaxIncomingAuth' "
553                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
554         { "subordinate", "[advertise]", 1, 2, 0, ARG_DB|ARG_MAGIC,
555                 &config_subordinate, "( OLcfgDbAt:0.15 NAME 'olcSubordinate' "
556                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
557         { "suffix",     "suffix", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
558                 &config_suffix, "( OLcfgDbAt:0.10 NAME 'olcSuffix' "
559                         "EQUALITY distinguishedNameMatch "
560                         "SYNTAX OMsDN )", NULL, NULL },
561         { "syncrepl", NULL, 0, 0, 0, ARG_DB|ARG_MAGIC,
562                 &syncrepl_config, "( OLcfgDbAt:0.11 NAME 'olcSyncrepl' "
563                         "EQUALITY caseIgnoreMatch "
564                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
565         { "threads", "count", 2, 2, 0,
566 #ifdef NO_THREADS
567                 ARG_IGNORED, NULL,
568 #else
569                 ARG_INT|ARG_MAGIC|CFG_THREADS, &config_generic,
570 #endif
571                 "( OLcfgGlAt:66 NAME 'olcThreads' "
572                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
573         { "timelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
574                 &config_timelimit, "( OLcfgGlAt:67 NAME 'olcTimeLimit' "
575                         "SYNTAX OMsDirectoryString )", NULL, NULL },
576         { "TLSCACertificateFile", NULL, 0, 0, 0,
577 #ifdef HAVE_TLS
578                 CFG_TLS_CA_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
579 #else
580                 ARG_IGNORED, NULL,
581 #endif
582                 "( OLcfgGlAt:68 NAME 'olcTLSCACertificateFile' "
583                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
584         { "TLSCACertificatePath", NULL, 0, 0, 0,
585 #ifdef HAVE_TLS
586                 CFG_TLS_CA_PATH|ARG_STRING|ARG_MAGIC, &config_tls_option,
587 #else
588                 ARG_IGNORED, NULL,
589 #endif
590                 "( OLcfgGlAt:69 NAME 'olcTLSCACertificatePath' "
591                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
592         { "TLSCertificateFile", NULL, 0, 0, 0,
593 #ifdef HAVE_TLS
594                 CFG_TLS_CERT_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
595 #else
596                 ARG_IGNORED, NULL,
597 #endif
598                 "( OLcfgGlAt:70 NAME 'olcTLSCertificateFile' "
599                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
600         { "TLSCertificateKeyFile", NULL, 0, 0, 0,
601 #ifdef HAVE_TLS
602                 CFG_TLS_CERT_KEY|ARG_STRING|ARG_MAGIC, &config_tls_option,
603 #else
604                 ARG_IGNORED, NULL,
605 #endif
606                 "( OLcfgGlAt:71 NAME 'olcTLSCertificateKeyFile' "
607                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
608         { "TLSCipherSuite",     NULL, 0, 0, 0,
609 #ifdef HAVE_TLS
610                 CFG_TLS_CIPHER|ARG_STRING|ARG_MAGIC, &config_tls_option,
611 #else
612                 ARG_IGNORED, NULL,
613 #endif
614                 "( OLcfgGlAt:72 NAME 'olcTLSCipherSuite' "
615                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
616         { "TLSCRLCheck", NULL, 0, 0, 0,
617 #if defined(HAVE_TLS) && defined(HAVE_OPENSSL_CRL)
618                 CFG_TLS_CRLCHECK|ARG_STRING|ARG_MAGIC, &config_tls_config,
619 #else
620                 ARG_IGNORED, NULL,
621 #endif
622                 "( OLcfgGlAt:73 NAME 'olcTLSCRLCheck' "
623                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
624         { "TLSCRLFile", NULL, 0, 0, 0,
625 #if defined(HAVE_GNUTLS)
626                 CFG_TLS_CRL_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
627 #else
628                 ARG_IGNORED, NULL,
629 #endif
630                 "( OLcfgGlAt:82 NAME 'olcTLSCRLFile' "
631                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
632         { "TLSRandFile", NULL, 0, 0, 0,
633 #ifdef HAVE_TLS
634                 CFG_TLS_RAND|ARG_STRING|ARG_MAGIC, &config_tls_option,
635 #else
636                 ARG_IGNORED, NULL,
637 #endif
638                 "( OLcfgGlAt:74 NAME 'olcTLSRandFile' "
639                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
640         { "TLSVerifyClient", NULL, 0, 0, 0,
641 #ifdef HAVE_TLS
642                 CFG_TLS_VERIFY|ARG_STRING|ARG_MAGIC, &config_tls_config,
643 #else
644                 ARG_IGNORED, NULL,
645 #endif
646                 "( OLcfgGlAt:75 NAME 'olcTLSVerifyClient' "
647                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
648         { "TLSDHParamFile", NULL, 0, 0, 0,
649 #ifdef HAVE_TLS
650                 CFG_TLS_DH_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
651 #else
652                 ARG_IGNORED, NULL,
653 #endif
654                 "( OLcfgGlAt:77 NAME 'olcTLSDHParamFile' "
655                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
656         { "tool-threads", "count", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_TTHREADS,
657                 &config_generic, "( OLcfgGlAt:80 NAME 'olcToolThreads' "
658                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
659         { "ucdata-path", "path", 2, 2, 0, ARG_IGNORED,
660                 NULL, NULL, NULL, NULL },
661         { "updatedn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
662                 &config_updatedn, "( OLcfgDbAt:0.12 NAME 'olcUpdateDN' "
663                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
664         { "updateref", "url", 2, 2, 0, ARG_DB|ARG_MAGIC,
665                 &config_updateref, "( OLcfgDbAt:0.13 NAME 'olcUpdateRef' "
666                         "EQUALITY caseIgnoreMatch "
667                         "SUP labeledURI )", NULL, NULL },
668         { NULL, NULL, 0, 0, 0, ARG_IGNORED,
669                 NULL, NULL, NULL, NULL }
670 };
671
672 /* Routines to check if a child can be added to this type */
673 static ConfigLDAPadd cfAddSchema, cfAddInclude, cfAddDatabase,
674         cfAddBackend, cfAddModule, cfAddOverlay;
675
676 /* NOTE: be careful when defining array members
677  * that can be conditionally compiled */
678 #define CFOC_GLOBAL     cf_ocs[1]
679 #define CFOC_SCHEMA     cf_ocs[2]
680 #define CFOC_BACKEND    cf_ocs[3]
681 #define CFOC_DATABASE   cf_ocs[4]
682 #define CFOC_OVERLAY    cf_ocs[5]
683 #define CFOC_INCLUDE    cf_ocs[6]
684 #define CFOC_FRONTEND   cf_ocs[7]
685 #ifdef SLAPD_MODULES
686 #define CFOC_MODULE     cf_ocs[8]
687 #endif /* SLAPD_MODULES */
688
689 static ConfigOCs cf_ocs[] = {
690         { "( OLcfgGlOc:0 "
691                 "NAME 'olcConfig' "
692                 "DESC 'OpenLDAP configuration object' "
693                 "ABSTRACT SUP top )", Cft_Abstract, NULL },
694         { "( OLcfgGlOc:1 "
695                 "NAME 'olcGlobal' "
696                 "DESC 'OpenLDAP Global configuration options' "
697                 "SUP olcConfig STRUCTURAL "
698                 "MAY ( cn $ olcConfigFile $ olcConfigDir $ olcAllows $ olcArgsFile $ "
699                  "olcAttributeOptions $ olcAuthIDRewrite $ "
700                  "olcAuthzPolicy $ olcAuthzRegexp $ olcConcurrency $ "
701                  "olcConnMaxPending $ olcConnMaxPendingAuth $ "
702                  "olcDisallows $ olcGentleHUP $ olcIdleTimeout $ "
703                  "olcIndexSubstrIfMaxLen $ olcIndexSubstrIfMinLen $ "
704                  "olcIndexSubstrAnyLen $ olcIndexSubstrAnyStep $ olcLocalSSF $ "
705                  "olcLogLevel $ "
706                  "olcPasswordCryptSaltFormat $ olcPasswordHash $ olcPidFile $ "
707                  "olcPluginLogFile $ olcReadOnly $ olcReferral $ "
708                  "olcReplogFile $ olcRequires $ olcRestrict $ olcReverseLookup $ "
709                  "olcRootDSE $ "
710                  "olcSaslHost $ olcSaslRealm $ olcSaslSecProps $ "
711                  "olcSecurity $ olcServerID $ olcSizeLimit $ "
712                  "olcSockbufMaxIncoming $ olcSockbufMaxIncomingAuth $ "
713                  "olcThreads $ olcTimeLimit $ olcTLSCACertificateFile $ "
714                  "olcTLSCACertificatePath $ olcTLSCertificateFile $ "
715                  "olcTLSCertificateKeyFile $ olcTLSCipherSuite $ olcTLSCRLCheck $ "
716                  "olcTLSRandFile $ olcTLSVerifyClient $ olcTLSDHParamFile $ "
717                  "olcTLSCRLFile $ olcToolThreads $ "
718                  "olcObjectIdentifier $ olcAttributeTypes $ olcObjectClasses $ "
719                  "olcDitContentRules ) )", Cft_Global },
720         { "( OLcfgGlOc:2 "
721                 "NAME 'olcSchemaConfig' "
722                 "DESC 'OpenLDAP schema object' "
723                 "SUP olcConfig STRUCTURAL "
724                 "MAY ( cn $ olcObjectIdentifier $ olcAttributeTypes $ "
725                  "olcObjectClasses $ olcDitContentRules ) )",
726                         Cft_Schema, NULL, cfAddSchema },
727         { "( OLcfgGlOc:3 "
728                 "NAME 'olcBackendConfig' "
729                 "DESC 'OpenLDAP Backend-specific options' "
730                 "SUP olcConfig STRUCTURAL "
731                 "MUST olcBackend )", Cft_Backend, NULL, cfAddBackend },
732         { "( OLcfgGlOc:4 "
733                 "NAME 'olcDatabaseConfig' "
734                 "DESC 'OpenLDAP Database-specific options' "
735                 "SUP olcConfig STRUCTURAL "
736                 "MUST olcDatabase "
737                 "MAY ( olcHidden $ olcSuffix $ olcSubordinate $ olcAccess $ "
738                  "olcLastMod $ olcLimits $ "
739                  "olcMaxDerefDepth $ olcPlugin $ olcReadOnly $ olcReplica $ "
740                  "olcReplicaArgsFile $ olcReplicaPidFile $ olcReplicationInterval $ "
741                  "olcReplogFile $ olcRequires $ olcRestrict $ olcRootDN $ olcRootPW $ "
742                  "olcSchemaDN $ olcSecurity $ olcSizeLimit $ olcSyncrepl $ "
743                  "olcTimeLimit $ olcUpdateDN $ olcUpdateRef $ olcMirrorMode $ "
744                  "olcMonitoring ) )",
745                         Cft_Database, NULL, cfAddDatabase },
746         { "( OLcfgGlOc:5 "
747                 "NAME 'olcOverlayConfig' "
748                 "DESC 'OpenLDAP Overlay-specific options' "
749                 "SUP olcConfig STRUCTURAL "
750                 "MUST olcOverlay )", Cft_Overlay, NULL, cfAddOverlay },
751         { "( OLcfgGlOc:6 "
752                 "NAME 'olcIncludeFile' "
753                 "DESC 'OpenLDAP configuration include file' "
754                 "SUP olcConfig STRUCTURAL "
755                 "MUST olcInclude "
756                 "MAY ( cn $ olcRootDSE ) )",
757                 /* Used to be Cft_Include, that def has been removed */
758                 Cft_Abstract, NULL, cfAddInclude },
759         /* This should be STRUCTURAL like all the other database classes, but
760          * that would mean inheriting all of the olcDatabaseConfig attributes,
761          * which causes them to be merged twice in config_build_entry.
762          */
763         { "( OLcfgGlOc:7 "
764                 "NAME 'olcFrontendConfig' "
765                 "DESC 'OpenLDAP frontend configuration' "
766                 "AUXILIARY "
767                 "MAY ( olcDefaultSearchBase $ olcPasswordHash ) )",
768                 Cft_Database, NULL, NULL },
769 #ifdef SLAPD_MODULES
770         { "( OLcfgGlOc:8 "
771                 "NAME 'olcModuleList' "
772                 "DESC 'OpenLDAP dynamic module info' "
773                 "SUP olcConfig STRUCTURAL "
774                 "MAY ( cn $ olcModulePath $ olcModuleLoad ) )",
775                 Cft_Module, NULL, cfAddModule },
776 #endif
777         { NULL, 0, NULL }
778 };
779
780 typedef struct ServerID {
781         struct ServerID *si_next;
782         struct berval si_url;
783         int si_num;
784 } ServerID;
785
786 static ServerID *sid_list;
787
788 static int
789 config_generic(ConfigArgs *c) {
790         int i;
791
792         if ( c->op == SLAP_CONFIG_EMIT ) {
793                 int rc = 0;
794                 switch(c->type) {
795                 case CFG_CONCUR:
796                         c->value_int = ldap_pvt_thread_get_concurrency();
797                         break;
798                 case CFG_THREADS:
799                         c->value_int = connection_pool_max;
800                         break;
801                 case CFG_TTHREADS:
802                         c->value_int = slap_tool_thread_max;
803                         break;
804                 case CFG_SALT:
805                         if ( passwd_salt )
806                                 c->value_string = ch_strdup( passwd_salt );
807                         else
808                                 rc = 1;
809                         break;
810                 case CFG_LIMITS:
811                         if ( c->be->be_limits ) {
812                                 char buf[4096*3];
813                                 struct berval bv;
814
815                                 for ( i=0; c->be->be_limits[i]; i++ ) {
816                                         bv.bv_len = snprintf( buf, sizeof( buf ), SLAP_X_ORDERED_FMT, i );
817                                         if ( bv.bv_len >= sizeof( buf ) ) {
818                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
819                                                 c->rvalue_vals = NULL;
820                                                 rc = 1;
821                                                 break;
822                                         }
823                                         bv.bv_val = buf + bv.bv_len;
824                                         limits_unparse( c->be->be_limits[i], &bv,
825                                                         sizeof( buf ) - ( bv.bv_val - buf ) );
826                                         bv.bv_len += bv.bv_val - buf;
827                                         bv.bv_val = buf;
828                                         value_add_one( &c->rvalue_vals, &bv );
829                                 }
830                         }
831                         if ( !c->rvalue_vals ) rc = 1;
832                         break;
833                 case CFG_RO:
834                         c->value_int = (c->be->be_restrictops & SLAP_RESTRICT_OP_WRITES) ==
835                                 SLAP_RESTRICT_OP_WRITES;
836                         break;
837                 case CFG_AZPOLICY:
838                         c->value_string = ch_strdup( slap_sasl_getpolicy());
839                         break;
840                 case CFG_AZREGEXP:
841                         slap_sasl_regexp_unparse( &c->rvalue_vals );
842                         if ( !c->rvalue_vals ) rc = 1;
843                         break;
844 #ifdef HAVE_CYRUS_SASL
845                 case CFG_SASLSECP: {
846                         struct berval bv = BER_BVNULL;
847                         slap_sasl_secprops_unparse( &bv );
848                         if ( !BER_BVISNULL( &bv )) {
849                                 ber_bvarray_add( &c->rvalue_vals, &bv );
850                         } else {
851                                 rc = 1;
852                         }
853                         }
854                         break;
855 #endif
856                 case CFG_DEPTH:
857                         c->value_int = c->be->be_max_deref_depth;
858                         break;
859                 case CFG_HIDDEN:
860                         if ( SLAP_DBHIDDEN( c->be )) {
861                                 c->value_int = 1;
862                         } else {
863                                 rc = 1;
864                         }
865                         break;
866                 case CFG_OID: {
867                         ConfigFile *cf = c->private;
868                         if ( !cf )
869                                 oidm_unparse( &c->rvalue_vals, NULL, NULL, 1 );
870                         else if ( cf->c_om_head )
871                                 oidm_unparse( &c->rvalue_vals, cf->c_om_head,
872                                         cf->c_om_tail, 0 );
873                         if ( !c->rvalue_vals )
874                                 rc = 1;
875                         }
876                         break;
877                 case CFG_ATOPT:
878                         ad_unparse_options( &c->rvalue_vals );
879                         break;
880                 case CFG_OC: {
881                         ConfigFile *cf = c->private;
882                         if ( !cf )
883                                 oc_unparse( &c->rvalue_vals, NULL, NULL, 1 );
884                         else if ( cf->c_oc_head )
885                                 oc_unparse( &c->rvalue_vals, cf->c_oc_head,
886                                         cf->c_oc_tail, 0 );
887                         if ( !c->rvalue_vals )
888                                 rc = 1;
889                         }
890                         break;
891                 case CFG_ATTR: {
892                         ConfigFile *cf = c->private;
893                         if ( !cf )
894                                 at_unparse( &c->rvalue_vals, NULL, NULL, 1 );
895                         else if ( cf->c_at_head )
896                                 at_unparse( &c->rvalue_vals, cf->c_at_head,
897                                         cf->c_at_tail, 0 );
898                         if ( !c->rvalue_vals )
899                                 rc = 1;
900                         }
901                         break;
902                 case CFG_DIT: {
903                         ConfigFile *cf = c->private;
904                         if ( !cf )
905                                 cr_unparse( &c->rvalue_vals, NULL, NULL, 1 );
906                         else if ( cf->c_cr_head )
907                                 cr_unparse( &c->rvalue_vals, cf->c_cr_head,
908                                         cf->c_cr_tail, 0 );
909                         if ( !c->rvalue_vals )
910                                 rc = 1;
911                         }
912                         break;
913                         
914                 case CFG_ACL: {
915                         AccessControl *a;
916                         char *src, *dst, ibuf[11];
917                         struct berval bv, abv;
918                         for (i=0, a=c->be->be_acl; a; i++,a=a->acl_next) {
919                                 abv.bv_len = snprintf( ibuf, sizeof( ibuf ), SLAP_X_ORDERED_FMT, i );
920                                 if ( abv.bv_len >= sizeof( ibuf ) ) {
921                                         ber_bvarray_free_x( c->rvalue_vals, NULL );
922                                         c->rvalue_vals = NULL;
923                                         i = 0;
924                                         break;
925                                 }
926                                 acl_unparse( a, &bv );
927                                 abv.bv_val = ch_malloc( abv.bv_len + bv.bv_len + 1 );
928                                 AC_MEMCPY( abv.bv_val, ibuf, abv.bv_len );
929                                 /* Turn TAB / EOL into plain space */
930                                 for (src=bv.bv_val,dst=abv.bv_val+abv.bv_len; *src; src++) {
931                                         if (isspace((unsigned char)*src)) *dst++ = ' ';
932                                         else *dst++ = *src;
933                                 }
934                                 *dst = '\0';
935                                 if (dst[-1] == ' ') {
936                                         dst--;
937                                         *dst = '\0';
938                                 }
939                                 abv.bv_len = dst - abv.bv_val;
940                                 ber_bvarray_add( &c->rvalue_vals, &abv );
941                         }
942                         rc = (!i);
943                         break;
944                 }
945                 case CFG_ROOTDSE: {
946                         ConfigFile *cf = c->private;
947                         if ( cf->c_dseFiles ) {
948                                 value_add( &c->rvalue_vals, cf->c_dseFiles );
949                         } else {
950                                 rc = 1;
951                         }
952                         }
953                         break;
954                 case CFG_SERVERID:
955                         if ( sid_list ) {
956                                 ServerID *si;
957                                 struct berval bv;
958
959                                 for ( si = sid_list; si; si=si->si_next ) {
960                                         assert( si->si_num >= 0 && si->si_num <= SLAP_SYNC_SID_MAX );
961                                         if ( !BER_BVISEMPTY( &si->si_url )) {
962                                                 bv.bv_len = si->si_url.bv_len + 6;
963                                                 bv.bv_val = ch_malloc( bv.bv_len );
964                                                 sprintf( bv.bv_val, "%d %s", si->si_num,
965                                                         si->si_url.bv_val );
966                                                 ber_bvarray_add( &c->rvalue_vals, &bv );
967                                         } else {
968                                                 char buf[5];
969                                                 bv.bv_val = buf;
970                                                 bv.bv_len = sprintf( buf, "%d", si->si_num );
971                                                 value_add_one( &c->rvalue_vals, &bv );
972                                         }
973                                 }
974                         } else {
975                                 rc = 1;
976                         }
977                         break;
978                 case CFG_LOGFILE:
979                         if ( logfileName )
980                                 c->value_string = ch_strdup( logfileName );
981                         else
982                                 rc = 1;
983                         break;
984                 case CFG_LASTMOD:
985                         c->value_int = (SLAP_NOLASTMOD(c->be) == 0);
986                         break;
987                 case CFG_MIRRORMODE:
988                         if ( SLAP_SHADOW(c->be))
989                                 c->value_int = (SLAP_SINGLE_SHADOW(c->be) == 0);
990                         else
991                                 rc = 1;
992                         break;
993                 case CFG_MONITORING:
994                         c->value_int = (SLAP_DBMONITORING(c->be) != 0);
995                         break;
996                 case CFG_SSTR_IF_MAX:
997                         c->value_int = index_substr_if_maxlen;
998                         break;
999                 case CFG_SSTR_IF_MIN:
1000                         c->value_int = index_substr_if_minlen;
1001                         break;
1002 #ifdef SLAPD_MODULES
1003                 case CFG_MODLOAD: {
1004                         ModPaths *mp = c->private;
1005                         if (mp->mp_loads) {
1006                                 int i;
1007                                 for (i=0; !BER_BVISNULL(&mp->mp_loads[i]); i++) {
1008                                         struct berval bv;
1009                                         bv.bv_val = c->log;
1010                                         bv.bv_len = snprintf( bv.bv_val, sizeof( c->log ),
1011                                                 SLAP_X_ORDERED_FMT "%s", i,
1012                                                 mp->mp_loads[i].bv_val );
1013                                         if ( bv.bv_len >= sizeof( c->log ) ) {
1014                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
1015                                                 c->rvalue_vals = NULL;
1016                                                 break;
1017                                         }
1018                                         value_add_one( &c->rvalue_vals, &bv );
1019                                 }
1020                         }
1021
1022                         rc = c->rvalue_vals ? 0 : 1;
1023                         }
1024                         break;
1025                 case CFG_MODPATH: {
1026                         ModPaths *mp = c->private;
1027                         if ( !BER_BVISNULL( &mp->mp_path ))
1028                                 value_add_one( &c->rvalue_vals, &mp->mp_path );
1029
1030                         rc = c->rvalue_vals ? 0 : 1;
1031                         }
1032                         break;
1033 #endif
1034 #ifdef LDAP_SLAPI
1035                 case CFG_PLUGIN:
1036                         slapi_int_plugin_unparse( c->be, &c->rvalue_vals );
1037                         if ( !c->rvalue_vals ) rc = 1;
1038                         break;
1039 #endif
1040 #ifdef SLAP_AUTH_REWRITE
1041                 case CFG_REWRITE:
1042                         if ( authz_rewrites ) {
1043                                 struct berval bv, idx;
1044                                 char ibuf[32];
1045                                 int i;
1046
1047                                 idx.bv_val = ibuf;
1048                                 for ( i=0; !BER_BVISNULL( &authz_rewrites[i] ); i++ ) {
1049                                         idx.bv_len = snprintf( idx.bv_val, sizeof( ibuf ), SLAP_X_ORDERED_FMT, i );
1050                                         if ( idx.bv_len >= sizeof( ibuf ) ) {
1051                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
1052                                                 c->rvalue_vals = NULL;
1053                                                 break;
1054                                         }
1055                                         bv.bv_len = idx.bv_len + authz_rewrites[i].bv_len;
1056                                         bv.bv_val = ch_malloc( bv.bv_len + 1 );
1057                                         AC_MEMCPY( bv.bv_val, idx.bv_val, idx.bv_len );
1058                                         AC_MEMCPY( &bv.bv_val[ idx.bv_len ],
1059                                                 authz_rewrites[i].bv_val,
1060                                                 authz_rewrites[i].bv_len + 1 );
1061                                         ber_bvarray_add( &c->rvalue_vals, &bv );
1062                                 }
1063                         }
1064                         if ( !c->rvalue_vals ) rc = 1;
1065                         break;
1066 #endif
1067                 default:
1068                         rc = 1;
1069                 }
1070                 return rc;
1071         } else if ( c->op == LDAP_MOD_DELETE ) {
1072                 int rc = 0;
1073                 switch(c->type) {
1074                 /* single-valued attrs, no-ops */
1075                 case CFG_CONCUR:
1076                 case CFG_THREADS:
1077                 case CFG_TTHREADS:
1078                 case CFG_RO:
1079                 case CFG_AZPOLICY:
1080                 case CFG_DEPTH:
1081                 case CFG_LASTMOD:
1082                 case CFG_MIRRORMODE:
1083                 case CFG_MONITORING:
1084                 case CFG_SASLSECP:
1085                 case CFG_SSTR_IF_MAX:
1086                 case CFG_SSTR_IF_MIN:
1087                         break;
1088
1089                 /* no-ops, requires slapd restart */
1090                 case CFG_PLUGIN:
1091                 case CFG_MODLOAD:
1092                 case CFG_AZREGEXP:
1093                 case CFG_REWRITE:
1094                         snprintf(c->log, sizeof( c->log ), "change requires slapd restart");
1095                         break;
1096
1097                 case CFG_SALT:
1098                         ch_free( passwd_salt );
1099                         passwd_salt = NULL;
1100                         break;
1101
1102                 case CFG_LOGFILE:
1103                         ch_free( logfileName );
1104                         logfileName = NULL;
1105                         break;
1106
1107                 case CFG_SERVERID: {
1108                         ServerID *si, **sip;
1109
1110                         for ( i=0, si = sid_list, sip = &sid_list;
1111                                 si; si = *sip, i++ ) {
1112                                 if ( c->valx == -1 || i == c->valx ) {
1113                                         *sip = si->si_next;
1114                                         ch_free( si );
1115                                         if ( c->valx >= 0 )
1116                                                 break;
1117                                 } else {
1118                                         sip = &si->si_next;
1119                                 }
1120                         }
1121                         }
1122                         break;
1123                 case CFG_HIDDEN:
1124                         c->be->be_flags &= ~SLAP_DBFLAG_HIDDEN;
1125                         break;
1126
1127                 case CFG_ACL:
1128                         if ( c->valx < 0 ) {
1129                                 AccessControl *end;
1130                                 if ( c->be == frontendDB )
1131                                         end = NULL;
1132                                 else
1133                                         end = frontendDB->be_acl;
1134                                 acl_destroy( c->be->be_acl, end );
1135                                 c->be->be_acl = end;
1136
1137                         } else {
1138                                 AccessControl **prev, *a;
1139                                 int i;
1140                                 for (i=0, prev = &c->be->be_acl; i < c->valx;
1141                                         i++ ) {
1142                                         a = *prev;
1143                                         prev = &a->acl_next;
1144                                 }
1145                                 a = *prev;
1146                                 *prev = a->acl_next;
1147                                 acl_free( a );
1148                         }
1149                         break;
1150
1151                 case CFG_OC: {
1152                         CfEntryInfo *ce;
1153                         /* Can be NULL when undoing a failed add */
1154                         if ( c->ca_entry ) {
1155                                 ce = c->ca_entry->e_private;
1156                                 /* can't modify the hardcoded schema */
1157                                 if ( ce->ce_parent->ce_type == Cft_Global )
1158                                         return 1;
1159                                 }
1160                         }
1161                         cfn = c->private;
1162                         if ( c->valx < 0 ) {
1163                                 ObjectClass *oc;
1164
1165                                 for( oc = cfn->c_oc_head; oc; oc_next( &oc )) {
1166                                         oc_delete( oc );
1167                                         if ( oc  == cfn->c_oc_tail )
1168                                                 break;
1169                                 }
1170                                 cfn->c_oc_head = cfn->c_oc_tail = NULL;
1171                         } else {
1172                                 ObjectClass *oc, *prev = NULL;
1173
1174                                 for ( i=0, oc=cfn->c_oc_head; i<c->valx; i++) {
1175                                         prev = oc;
1176                                         oc_next( &oc );
1177                                 }
1178                                 oc_delete( oc );
1179                                 if ( cfn->c_oc_tail == oc ) {
1180                                         cfn->c_oc_tail = prev;
1181                                 }
1182                                 if ( cfn->c_oc_head == oc ) {
1183                                         oc_next( &oc );
1184                                         cfn->c_oc_head = oc;
1185                                 }
1186                         }
1187                         break;
1188
1189                 case CFG_ATTR: {
1190                         CfEntryInfo *ce;
1191                         /* Can be NULL when undoing a failed add */
1192                         if ( c->ca_entry ) {
1193                                 ce = c->ca_entry->e_private;
1194                                 /* can't modify the hardcoded schema */
1195                                 if ( ce->ce_parent->ce_type == Cft_Global )
1196                                         return 1;
1197                                 }
1198                         }
1199                         cfn = c->private;
1200                         if ( c->valx < 0 ) {
1201                                 AttributeType *at;
1202
1203                                 for( at = cfn->c_at_head; at; at_next( &at )) {
1204                                         at_delete( at );
1205                                         if ( at  == cfn->c_at_tail )
1206                                                 break;
1207                                 }
1208                                 cfn->c_at_head = cfn->c_at_tail = NULL;
1209                         } else {
1210                                 AttributeType *at, *prev = NULL;
1211
1212                                 for ( i=0, at=cfn->c_at_head; i<c->valx; i++) {
1213                                         prev = at;
1214                                         at_next( &at );
1215                                 }
1216                                 at_delete( at );
1217                                 if ( cfn->c_at_tail == at ) {
1218                                         cfn->c_at_tail = prev;
1219                                 }
1220                                 if ( cfn->c_at_head == at ) {
1221                                         at_next( &at );
1222                                         cfn->c_at_head = at;
1223                                 }
1224                         }
1225                         break;
1226
1227                 case CFG_LIMITS:
1228                         /* FIXME: there is no limits_free function */
1229                 case CFG_ATOPT:
1230                         /* FIXME: there is no ad_option_free function */
1231                 case CFG_ROOTDSE:
1232                         /* FIXME: there is no way to remove attributes added by
1233                                 a DSE file */
1234                 case CFG_OID:
1235                 case CFG_DIT:
1236                 case CFG_MODPATH:
1237                 default:
1238                         rc = 1;
1239                         break;
1240                 }
1241                 return rc;
1242         }
1243
1244         switch(c->type) {
1245                 case CFG_BACKEND:
1246                         if(!(c->bi = backend_info(c->argv[1]))) {
1247                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> failed init", c->argv[0] );
1248                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
1249                                         c->log, c->cr_msg, c->argv[1] );
1250                                 return(1);
1251                         }
1252                         break;
1253
1254                 case CFG_DATABASE:
1255                         c->bi = NULL;
1256                         /* NOTE: config is always the first backend!
1257                          */
1258                         if ( !strcasecmp( c->argv[1], "config" )) {
1259                                 c->be = LDAP_STAILQ_FIRST(&backendDB);
1260                         } else if ( !strcasecmp( c->argv[1], "frontend" )) {
1261                                 c->be = frontendDB;
1262                         } else {
1263                                 c->be = backend_db_init(c->argv[1], NULL, c->valx, &c->reply);
1264                                 if ( !c->be ) {
1265                                         if ( c->cr_msg[0] == 0 )
1266                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> failed init", c->argv[0] );
1267                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n", c->log, c->cr_msg, c->argv[1] );
1268                                         return(1);
1269                                 }
1270                         }
1271                         break;
1272
1273                 case CFG_CONCUR:
1274                         ldap_pvt_thread_set_concurrency(c->value_int);
1275                         break;
1276
1277                 case CFG_THREADS:
1278                         if ( c->value_int < 2 ) {
1279                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1280                                         "threads=%d smaller than minimum value 2",
1281                                         c->value_int );
1282                                 Debug(LDAP_DEBUG_ANY, "%s: %s.\n",
1283                                         c->log, c->cr_msg, 0 );
1284                                 return 1;
1285
1286                         } else if ( c->value_int > 2 * SLAP_MAX_WORKER_THREADS ) {
1287                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1288                                         "warning, threads=%d larger than twice the default (2*%d=%d); YMMV",
1289                                         c->value_int, SLAP_MAX_WORKER_THREADS, 2 * SLAP_MAX_WORKER_THREADS );
1290                                 Debug(LDAP_DEBUG_ANY, "%s: %s.\n",
1291                                         c->log, c->cr_msg, 0 );
1292                         }
1293                         if ( slapMode & SLAP_SERVER_MODE )
1294                                 ldap_pvt_thread_pool_maxthreads(&connection_pool, c->value_int);
1295                         connection_pool_max = c->value_int;     /* save for reference */
1296                         break;
1297
1298                 case CFG_TTHREADS:
1299                         if ( slapMode & SLAP_TOOL_MODE )
1300                                 ldap_pvt_thread_pool_maxthreads(&connection_pool, c->value_int);
1301                         slap_tool_thread_max = c->value_int;    /* save for reference */
1302                         break;
1303
1304                 case CFG_SALT:
1305                         if ( passwd_salt ) ch_free( passwd_salt );
1306                         passwd_salt = c->value_string;
1307                         lutil_salt_format(passwd_salt);
1308                         break;
1309
1310                 case CFG_LIMITS:
1311                         if(limits_parse(c->be, c->fname, c->lineno, c->argc, c->argv))
1312                                 return(1);
1313                         break;
1314
1315                 case CFG_RO:
1316                         if(c->value_int)
1317                                 c->be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1318                         else
1319                                 c->be->be_restrictops &= ~SLAP_RESTRICT_OP_WRITES;
1320                         break;
1321
1322                 case CFG_AZPOLICY:
1323                         ch_free(c->value_string);
1324                         if (slap_sasl_setpolicy( c->argv[1] )) {
1325                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1326                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1327                                         c->log, c->cr_msg, c->argv[1] );
1328                                 return(1);
1329                         }
1330                         break;
1331                 
1332                 case CFG_AZREGEXP:
1333                         if (slap_sasl_regexp_config( c->argv[1], c->argv[2] ))
1334                                 return(1);
1335                         break;
1336                                 
1337 #ifdef HAVE_CYRUS_SASL
1338                 case CFG_SASLSECP:
1339                         {
1340                         char *txt = slap_sasl_secprops( c->argv[1] );
1341                         if ( txt ) {
1342                                 snprintf( c->cr_msg, sizeof(c->cr_msg), "<%s> %s",
1343                                         c->argv[0], txt );
1344                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
1345                                 return(1);
1346                         }
1347                         break;
1348                         }
1349 #endif
1350
1351                 case CFG_DEPTH:
1352                         c->be->be_max_deref_depth = c->value_int;
1353                         break;
1354
1355                 case CFG_OID: {
1356                         OidMacro *om;
1357
1358                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1359                                 cfn = c->private;
1360                         if(parse_oidm(c, 1, &om))
1361                                 return(1);
1362                         if (!cfn->c_om_head) cfn->c_om_head = om;
1363                         cfn->c_om_tail = om;
1364                         }
1365                         break;
1366
1367                 case CFG_OC: {
1368                         ObjectClass *oc, *prev;
1369
1370                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1371                                 cfn = c->private;
1372                         if ( c->valx < 0 ) {
1373                                 prev = cfn->c_oc_tail;
1374                         } else {
1375                                 prev = NULL;
1376                                 /* If adding anything after the first, prev is easy */
1377                                 if ( c->valx ) {
1378                                         int i;
1379                                         for (i=0, oc = cfn->c_oc_head; i<c->valx; i++) {
1380                                                 prev = oc;
1381                                                 oc_next( &oc );
1382                                         }
1383                                 } else
1384                                 /* If adding the first, and head exists, find its prev */
1385                                         if (cfn->c_oc_head) {
1386                                         for ( oc_start( &oc ); oc != cfn->c_oc_head; ) {
1387                                                 prev = oc;
1388                                                 oc_next( &oc );
1389                                         }
1390                                 }
1391                                 /* else prev is NULL, append to end of global list */
1392                         }
1393                         if(parse_oc(c, &oc, prev)) return(1);
1394                         if (!cfn->c_oc_head) cfn->c_oc_head = oc;
1395                         if (cfn->c_oc_tail == prev) cfn->c_oc_tail = oc;
1396                         }
1397                         break;
1398
1399                 case CFG_ATTR: {
1400                         AttributeType *at, *prev;
1401
1402                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1403                                 cfn = c->private;
1404                         if ( c->valx < 0 ) {
1405                                 prev = cfn->c_at_tail;
1406                         } else {
1407                                 prev = NULL;
1408                                 /* If adding anything after the first, prev is easy */
1409                                 if ( c->valx ) {
1410                                         int i;
1411                                         for (i=0, at = cfn->c_at_head; i<c->valx; i++) {
1412                                                 prev = at;
1413                                                 at_next( &at );
1414                                         }
1415                                 } else
1416                                 /* If adding the first, and head exists, find its prev */
1417                                         if (cfn->c_at_head) {
1418                                         for ( at_start( &at ); at != cfn->c_at_head; ) {
1419                                                 prev = at;
1420                                                 at_next( &at );
1421                                         }
1422                                 }
1423                                 /* else prev is NULL, append to end of global list */
1424                         }
1425                         if(parse_at(c, &at, prev)) return(1);
1426                         if (!cfn->c_at_head) cfn->c_at_head = at;
1427                         if (cfn->c_at_tail == prev) cfn->c_at_tail = at;
1428                         }
1429                         break;
1430
1431                 case CFG_DIT: {
1432                         ContentRule *cr;
1433
1434                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1435                                 cfn = c->private;
1436                         if(parse_cr(c, &cr)) return(1);
1437                         if (!cfn->c_cr_head) cfn->c_cr_head = cr;
1438                         cfn->c_cr_tail = cr;
1439                         }
1440                         break;
1441
1442                 case CFG_ATOPT:
1443                         ad_define_option(NULL, NULL, 0);
1444                         for(i = 1; i < c->argc; i++)
1445                                 if(ad_define_option(c->argv[i], c->fname, c->lineno))
1446                                         return(1);
1447                         break;
1448
1449                 case CFG_ACL:
1450                         /* Don't append to the global ACL if we're on a specific DB */
1451                         i = c->valx;
1452                         if ( c->be != frontendDB && frontendDB->be_acl && c->valx == -1 ) {
1453                                 AccessControl *a;
1454                                 i = 0;
1455                                 for ( a=c->be->be_acl; a && a != frontendDB->be_acl;
1456                                         a = a->acl_next )
1457                                         i++;
1458                         }
1459                         if ( parse_acl(c->be, c->fname, c->lineno, c->argc, c->argv, i ) ) {
1460                                 return 1;
1461                         }
1462                         break;
1463
1464                 case CFG_ROOTDSE:
1465                         if(root_dse_read_file(c->argv[1])) {
1466                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> could not read file", c->argv[0] );
1467                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1468                                         c->log, c->cr_msg, c->argv[1] );
1469                                 return(1);
1470                         }
1471                         {
1472                                 struct berval bv;
1473                                 ber_str2bv( c->argv[1], 0, 1, &bv );
1474                                 if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1475                                         cfn = c->private;
1476                                 ber_bvarray_add( &cfn->c_dseFiles, &bv );
1477                         }
1478                         break;
1479
1480                 case CFG_SERVERID:
1481                         {
1482                                 ServerID *si, **sip;
1483                                 LDAPURLDesc *lud;
1484                                 int num;
1485                                 if ( lutil_atoi( &num, c->argv[1] ) ||
1486                                         num < 0 || num > SLAP_SYNC_SID_MAX )
1487                                 {
1488                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
1489                                                 "<%s> illegal server ID", c->argv[0] );
1490                                         Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1491                                                 c->log, c->cr_msg, c->argv[1] );
1492                                         return 1;
1493                                 }
1494                                 /* only one value allowed if no URL is given */
1495                                 if ( c->argc > 2 ) {
1496                                         int len;
1497
1498                                         if ( sid_list && BER_BVISEMPTY( &sid_list->si_url )) {
1499                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1500                                                         "<%s> only one server ID allowed now", c->argv[0] );
1501                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1502                                                         c->log, c->cr_msg, c->argv[1] );
1503                                                 return 1;
1504                                         }
1505
1506                                         if ( ldap_url_parse( c->argv[2], &lud )) {
1507                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1508                                                         "<%s> invalid URL", c->argv[0] );
1509                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1510                                                         c->log, c->cr_msg, c->argv[2] );
1511                                                 return 1;
1512                                         }
1513                                         len = strlen( c->argv[2] );
1514                                         si = ch_malloc( sizeof(ServerID) + len + 1 );
1515                                         si->si_url.bv_val = (char *)(si+1);
1516                                         si->si_url.bv_len = len;
1517                                         strcpy( si->si_url.bv_val, c->argv[2] );
1518                                 } else {
1519                                         if ( sid_list ) {
1520                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1521                                                         "<%s> unqualified server ID not allowed now", c->argv[0] );
1522                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1523                                                         c->log, c->cr_msg, c->argv[1] );
1524                                                 return 1;
1525                                         }
1526                                         si = ch_malloc( sizeof(ServerID) );
1527                                         BER_BVZERO( &si->si_url );
1528                                         slap_serverID = num;
1529                                         Debug( LDAP_DEBUG_CONFIG,
1530                                                 "%s: SID=%d\n",
1531                                                 c->log, slap_serverID, 0 );
1532                                 }
1533                                 si->si_next = NULL;
1534                                 si->si_num = num;
1535                                 for ( sip = &sid_list; *sip; sip = &(*sip)->si_next );
1536                                 *sip = si;
1537
1538                                 if (( slapMode & SLAP_SERVER_MODE ) && c->argc > 2 ) {
1539                                         /* If hostname is empty, or is localhost, or matches
1540                                          * our hostname, this serverID refers to this host.
1541                                          * Compare it against listeners and ports.
1542                                          */
1543                                         if ( !lud->lud_host || !lud->lud_host[0] ||
1544                                                 !strncasecmp("localhost", lud->lud_host,
1545                                                         STRLENOF("localhost")) ||
1546                                                 !strcasecmp( global_host, lud->lud_host )) {
1547                                                 Listener **l = slapd_get_listeners();
1548                                                 int i;
1549
1550                                                 for ( i=0; l[i]; i++ ) {
1551                                                         LDAPURLDesc *lu2;
1552                                                         int isMe = 0;
1553                                                         ldap_url_parse( l[i]->sl_url.bv_val, &lu2 );
1554                                                         do {
1555                                                                 if ( strcasecmp( lud->lud_scheme,
1556                                                                         lu2->lud_scheme ))
1557                                                                         break;
1558                                                                 if ( lud->lud_port != lu2->lud_port )
1559                                                                         break;
1560                                                                 /* Listener on ANY address */
1561                                                                 if ( !lu2->lud_host || !lu2->lud_host[0] ) {
1562                                                                         isMe = 1;
1563                                                                         break;
1564                                                                 }
1565                                                                 /* URL on ANY address */
1566                                                                 if ( !lud->lud_host || !lud->lud_host[0] ) {
1567                                                                         isMe = 1;
1568                                                                         break;
1569                                                                 }
1570                                                                 /* Listener has specific host, must
1571                                                                  * match it
1572                                                                  */
1573                                                                 if ( !strcasecmp( lud->lud_host,
1574                                                                         lu2->lud_host )) {
1575                                                                         isMe = 1;
1576                                                                         break;
1577                                                                 }
1578                                                         } while(0);
1579                                                         ldap_free_urldesc( lu2 );
1580                                                         if ( isMe ) {
1581                                                                 slap_serverID = si->si_num;
1582                                                                 Debug( LDAP_DEBUG_CONFIG,
1583                                                                         "%s: SID=%d (listener=%s)\n",
1584                                                                         c->log, slap_serverID,
1585                                                                         l[i]->sl_url.bv_val );
1586                                                                 break;
1587                                                         }
1588                                                 }
1589                                         }
1590                                 }
1591                                 if ( c->argc > 2 )
1592                                         ldap_free_urldesc( lud );
1593                         }
1594                         break;
1595                 case CFG_LOGFILE: {
1596                                 FILE *logfile;
1597                                 if ( logfileName ) ch_free( logfileName );
1598                                 logfileName = c->value_string;
1599                                 logfile = fopen(logfileName, "w");
1600                                 if(logfile) lutil_debug_file(logfile);
1601                         } break;
1602
1603                 case CFG_LASTMOD:
1604                         if(SLAP_NOLASTMODCMD(c->be)) {
1605                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> not available for %s database",
1606                                         c->argv[0], c->be->bd_info->bi_type );
1607                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1608                                         c->log, c->cr_msg, 0 );
1609                                 return(1);
1610                         }
1611                         if(c->value_int)
1612                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_NOLASTMOD;
1613                         else
1614                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NOLASTMOD;
1615                         break;
1616
1617                 case CFG_MIRRORMODE:
1618                         if(!SLAP_SHADOW(c->be)) {
1619                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database is not a shadow",
1620                                         c->argv[0] );
1621                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1622                                         c->log, c->cr_msg, 0 );
1623                                 return(1);
1624                         }
1625                         if(c->value_int)
1626                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_SINGLE_SHADOW;
1627                         else
1628                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_SINGLE_SHADOW;
1629                         break;
1630
1631                 case CFG_MONITORING:
1632                         if(c->value_int)
1633                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_MONITORING;
1634                         else
1635                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_MONITORING;
1636                         break;
1637
1638                 case CFG_HIDDEN:
1639                         if (c->value_int)
1640                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_HIDDEN;
1641                         else
1642                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_HIDDEN;
1643                         break;
1644
1645                 case CFG_SSTR_IF_MAX:
1646                         if (c->value_int < index_substr_if_minlen) {
1647                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1648                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1649                                         c->log, c->cr_msg, c->value_int );
1650                                 return(1);
1651                         }
1652                         index_substr_if_maxlen = c->value_int;
1653                         break;
1654
1655                 case CFG_SSTR_IF_MIN:
1656                         if (c->value_int > index_substr_if_maxlen) {
1657                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1658                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1659                                         c->log, c->cr_msg, c->value_int );
1660                                 return(1);
1661                         }
1662                         index_substr_if_minlen = c->value_int;
1663                         break;
1664
1665 #ifdef SLAPD_MODULES
1666                 case CFG_MODLOAD:
1667                         /* If we're just adding a module on an existing modpath,
1668                          * make sure we've selected the current path.
1669                          */
1670                         if ( c->op == LDAP_MOD_ADD && c->private && modcur != c->private ) {
1671                                 modcur = c->private;
1672                                 /* This should never fail */
1673                                 if ( module_path( modcur->mp_path.bv_val )) {
1674                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> module path no longer valid",
1675                                                 c->argv[0] );
1676                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1677                                                 c->log, c->cr_msg, modcur->mp_path.bv_val );
1678                                         return(1);
1679                                 }
1680                         }
1681                         if(module_load(c->argv[1], c->argc - 2, (c->argc > 2) ? c->argv + 2 : NULL))
1682                                 return(1);
1683                         /* Record this load on the current path */
1684                         {
1685                                 struct berval bv;
1686                                 char *ptr;
1687                                 if ( c->op == SLAP_CONFIG_ADD ) {
1688                                         ptr = c->line + STRLENOF("moduleload");
1689                                         while (!isspace((unsigned char) *ptr)) ptr++;
1690                                         while (isspace((unsigned char) *ptr)) ptr++;
1691                                 } else {
1692                                         ptr = c->line;
1693                                 }
1694                                 ber_str2bv(ptr, 0, 1, &bv);
1695                                 ber_bvarray_add( &modcur->mp_loads, &bv );
1696                         }
1697                         /* Check for any new hardcoded schema */
1698                         if ( c->op == LDAP_MOD_ADD && CONFIG_ONLINE_ADD( c )) {
1699                                 config_check_schema( NULL, &cfBackInfo );
1700                         }
1701                         break;
1702
1703                 case CFG_MODPATH:
1704                         if(module_path(c->argv[1])) return(1);
1705                         /* Record which path was used with each module */
1706                         {
1707                                 ModPaths *mp;
1708
1709                                 if (!modpaths.mp_loads) {
1710                                         mp = &modpaths;
1711                                 } else {
1712                                         mp = ch_malloc( sizeof( ModPaths ));
1713                                         modlast->mp_next = mp;
1714                                 }
1715                                 ber_str2bv(c->argv[1], 0, 1, &mp->mp_path);
1716                                 mp->mp_next = NULL;
1717                                 mp->mp_loads = NULL;
1718                                 modlast = mp;
1719                                 c->private = mp;
1720                                 modcur = mp;
1721                         }
1722                         
1723                         break;
1724 #endif
1725
1726 #ifdef LDAP_SLAPI
1727                 case CFG_PLUGIN:
1728                         if(slapi_int_read_config(c->be, c->fname, c->lineno, c->argc, c->argv) != LDAP_SUCCESS)
1729                                 return(1);
1730                         slapi_plugins_used++;
1731                         break;
1732 #endif
1733
1734 #ifdef SLAP_AUTH_REWRITE
1735                 case CFG_REWRITE: {
1736                         struct berval bv;
1737                         char *line;
1738                         
1739                         if(slap_sasl_rewrite_config(c->fname, c->lineno, c->argc, c->argv))
1740                                 return(1);
1741
1742                         if ( c->argc > 1 ) {
1743                                 char    *s;
1744
1745                                 /* quote all args but the first */
1746                                 line = ldap_charray2str( c->argv, "\" \"" );
1747                                 ber_str2bv( line, 0, 0, &bv );
1748                                 s = ber_bvchr( &bv, '"' );
1749                                 assert( s != NULL );
1750                                 /* move the trailing quote of argv[0] to the end */
1751                                 AC_MEMCPY( s, s + 1, bv.bv_len - ( s - bv.bv_val ) );
1752                                 bv.bv_val[ bv.bv_len - 1 ] = '"';
1753
1754                         } else {
1755                                 ber_str2bv( c->argv[ 0 ], 0, 1, &bv );
1756                         }
1757                         
1758                         ber_bvarray_add( &authz_rewrites, &bv );
1759                         }
1760                         break;
1761 #endif
1762
1763
1764                 default:
1765                         Debug( LDAP_DEBUG_ANY,
1766                                 "%s: unknown CFG_TYPE %d.\n",
1767                                 c->log, c->type, 0 );
1768                         return 1;
1769
1770         }
1771         return(0);
1772 }
1773
1774
1775 static int
1776 config_fname(ConfigArgs *c) {
1777         if(c->op == SLAP_CONFIG_EMIT) {
1778                 if (c->private) {
1779                         ConfigFile *cf = c->private;
1780                         value_add_one( &c->rvalue_vals, &cf->c_file );
1781                         return 0;
1782                 }
1783                 return 1;
1784         }
1785         return(0);
1786 }
1787
1788 static int
1789 config_cfdir(ConfigArgs *c) {
1790         if(c->op == SLAP_CONFIG_EMIT) {
1791                 if ( !BER_BVISEMPTY( &cfdir )) {
1792                         value_add_one( &c->rvalue_vals, &cfdir );
1793                         return 0;
1794                 }
1795                 return 1;
1796         }
1797         return(0);
1798 }
1799
1800 static int
1801 config_search_base(ConfigArgs *c) {
1802         if(c->op == SLAP_CONFIG_EMIT) {
1803                 int rc = 1;
1804                 if (!BER_BVISEMPTY(&default_search_base)) {
1805                         value_add_one(&c->rvalue_vals, &default_search_base);
1806                         value_add_one(&c->rvalue_nvals, &default_search_nbase);
1807                         rc = 0;
1808                 }
1809                 return rc;
1810         } else if( c->op == LDAP_MOD_DELETE ) {
1811                 ch_free( default_search_base.bv_val );
1812                 ch_free( default_search_nbase.bv_val );
1813                 BER_BVZERO( &default_search_base );
1814                 BER_BVZERO( &default_search_nbase );
1815                 return 0;
1816         }
1817
1818         if(c->bi || c->be != frontendDB) {
1819                 Debug(LDAP_DEBUG_ANY, "%s: defaultSearchBase line must appear "
1820                         "prior to any backend or database definition\n",
1821                         c->log, 0, 0);
1822                 return(1);
1823         }
1824
1825         if(default_search_nbase.bv_len) {
1826                 free(default_search_base.bv_val);
1827                 free(default_search_nbase.bv_val);
1828         }
1829
1830         default_search_base = c->value_dn;
1831         default_search_nbase = c->value_ndn;
1832         return(0);
1833 }
1834
1835 /* For RE23 compatibility we allow this in the global entry
1836  * but we now defer it to the frontend entry to allow modules
1837  * to load new hash types.
1838  */
1839 static int
1840 config_passwd_hash(ConfigArgs *c) {
1841         int i;
1842         if (c->op == SLAP_CONFIG_EMIT) {
1843                 struct berval bv;
1844                 /* Don't generate it in the global entry */
1845                 if ( c->table == Cft_Global )
1846                         return 1;
1847                 for (i=0; default_passwd_hash && default_passwd_hash[i]; i++) {
1848                         ber_str2bv(default_passwd_hash[i], 0, 0, &bv);
1849                         value_add_one(&c->rvalue_vals, &bv);
1850                 }
1851                 return i ? 0 : 1;
1852         } else if ( c->op == LDAP_MOD_DELETE ) {
1853                 /* Deleting from global is a no-op, only the frontendDB entry matters */
1854                 if ( c->table == Cft_Global )
1855                         return 0;
1856                 if ( c->valx < 0 ) {
1857                         ldap_charray_free( default_passwd_hash );
1858                         default_passwd_hash = NULL;
1859                 } else {
1860                         i = c->valx;
1861                         ch_free( default_passwd_hash[i] );
1862                         for (; default_passwd_hash[i]; i++ )
1863                                 default_passwd_hash[i] = default_passwd_hash[i+1];
1864                 }
1865                 return 0;
1866         }
1867         for(i = 1; i < c->argc; i++) {
1868                 if(!lutil_passwd_scheme(c->argv[i])) {
1869                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> scheme not available", c->argv[0] );
1870                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1871                                 c->log, c->cr_msg, c->argv[i]);
1872                 } else {
1873                         ldap_charray_add(&default_passwd_hash, c->argv[i]);
1874                 }
1875         }
1876         if(!default_passwd_hash) {
1877                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> no valid hashes found", c->argv[0] );
1878                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1879                         c->log, c->cr_msg, 0 );
1880                 return(1);
1881         }
1882         return(0);
1883 }
1884
1885 static int
1886 config_schema_dn(ConfigArgs *c) {
1887         if ( c->op == SLAP_CONFIG_EMIT ) {
1888                 int rc = 1;
1889                 if ( !BER_BVISEMPTY( &c->be->be_schemadn )) {
1890                         value_add_one(&c->rvalue_vals, &c->be->be_schemadn);
1891                         value_add_one(&c->rvalue_nvals, &c->be->be_schemandn);
1892                         rc = 0;
1893                 }
1894                 return rc;
1895         } else if ( c->op == LDAP_MOD_DELETE ) {
1896                 ch_free( c->be->be_schemadn.bv_val );
1897                 ch_free( c->be->be_schemandn.bv_val );
1898                 BER_BVZERO( &c->be->be_schemadn );
1899                 BER_BVZERO( &c->be->be_schemandn );
1900                 return 0;
1901         }
1902         ch_free( c->be->be_schemadn.bv_val );
1903         ch_free( c->be->be_schemandn.bv_val );
1904         c->be->be_schemadn = c->value_dn;
1905         c->be->be_schemandn = c->value_ndn;
1906         return(0);
1907 }
1908
1909 static int
1910 config_sizelimit(ConfigArgs *c) {
1911         int i, rc = 0;
1912         struct slap_limits_set *lim = &c->be->be_def_limit;
1913         if (c->op == SLAP_CONFIG_EMIT) {
1914                 char buf[8192];
1915                 struct berval bv;
1916                 bv.bv_val = buf;
1917                 bv.bv_len = 0;
1918                 limits_unparse_one( lim, SLAP_LIMIT_SIZE, &bv, sizeof( buf ) );
1919                 if ( !BER_BVISEMPTY( &bv ))
1920                         value_add_one( &c->rvalue_vals, &bv );
1921                 else
1922                         rc = 1;
1923                 return rc;
1924         } else if ( c->op == LDAP_MOD_DELETE ) {
1925                 /* Reset to defaults */
1926                 lim->lms_s_soft = SLAPD_DEFAULT_SIZELIMIT;
1927                 lim->lms_s_hard = 0;
1928                 lim->lms_s_unchecked = -1;
1929                 lim->lms_s_pr = 0;
1930                 lim->lms_s_pr_hide = 0;
1931                 lim->lms_s_pr_total = 0;
1932                 return 0;
1933         }
1934         for(i = 1; i < c->argc; i++) {
1935                 if(!strncasecmp(c->argv[i], "size", 4)) {
1936                         rc = limits_parse_one(c->argv[i], lim);
1937                         if ( rc ) {
1938                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1939                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1940                                         c->log, c->cr_msg, c->argv[i]);
1941                                 return(1);
1942                         }
1943                 } else {
1944                         if(!strcasecmp(c->argv[i], "unlimited")) {
1945                                 lim->lms_s_soft = -1;
1946                         } else {
1947                                 if ( lutil_atoix( &lim->lms_s_soft, c->argv[i], 0 ) != 0 ) {
1948                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1949                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1950                                                 c->log, c->cr_msg, c->argv[i]);
1951                                         return(1);
1952                                 }
1953                         }
1954                         lim->lms_s_hard = 0;
1955                 }
1956         }
1957         return(0);
1958 }
1959
1960 static int
1961 config_timelimit(ConfigArgs *c) {
1962         int i, rc = 0;
1963         struct slap_limits_set *lim = &c->be->be_def_limit;
1964         if (c->op == SLAP_CONFIG_EMIT) {
1965                 char buf[8192];
1966                 struct berval bv;
1967                 bv.bv_val = buf;
1968                 bv.bv_len = 0;
1969                 limits_unparse_one( lim, SLAP_LIMIT_TIME, &bv, sizeof( buf ) );
1970                 if ( !BER_BVISEMPTY( &bv ))
1971                         value_add_one( &c->rvalue_vals, &bv );
1972                 else
1973                         rc = 1;
1974                 return rc;
1975         } else if ( c->op == LDAP_MOD_DELETE ) {
1976                 /* Reset to defaults */
1977                 lim->lms_t_soft = SLAPD_DEFAULT_TIMELIMIT;
1978                 lim->lms_t_hard = 0;
1979                 return 0;
1980         }
1981         for(i = 1; i < c->argc; i++) {
1982                 if(!strncasecmp(c->argv[i], "time", 4)) {
1983                         rc = limits_parse_one(c->argv[i], lim);
1984                         if ( rc ) {
1985                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1986                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1987                                         c->log, c->cr_msg, c->argv[i]);
1988                                 return(1);
1989                         }
1990                 } else {
1991                         if(!strcasecmp(c->argv[i], "unlimited")) {
1992                                 lim->lms_t_soft = -1;
1993                         } else {
1994                                 if ( lutil_atoix( &lim->lms_t_soft, c->argv[i], 0 ) != 0 ) {
1995                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1996                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1997                                                 c->log, c->cr_msg, c->argv[i]);
1998                                         return(1);
1999                                 }
2000                         }
2001                         lim->lms_t_hard = 0;
2002                 }
2003         }
2004         return(0);
2005 }
2006
2007 static int
2008 config_overlay(ConfigArgs *c) {
2009         if (c->op == SLAP_CONFIG_EMIT) {
2010                 return 1;
2011         } else if ( c->op == LDAP_MOD_DELETE ) {
2012                 assert(0);
2013         }
2014         if(c->argv[1][0] == '-' && overlay_config(c->be, &c->argv[1][1],
2015                 c->valx, &c->bi)) {
2016                 /* log error */
2017                 Debug( LDAP_DEBUG_ANY,
2018                         "%s: (optional) %s overlay \"%s\" configuration failed.\n",
2019                         c->log, c->be == frontendDB ? "global " : "", &c->argv[1][1]);
2020                 return 1;
2021         } else if(overlay_config(c->be, c->argv[1], c->valx, &c->bi)) {
2022                 return(1);
2023         }
2024         return(0);
2025 }
2026
2027 static int
2028 config_subordinate(ConfigArgs *c)
2029 {
2030         int rc = 1;
2031         int advertise;
2032
2033         switch( c->op ) {
2034         case SLAP_CONFIG_EMIT:
2035                 if ( SLAP_GLUE_SUBORDINATE( c->be )) {
2036                         struct berval bv;
2037
2038                         bv.bv_val = SLAP_GLUE_ADVERTISE( c->be ) ? "advertise" : "TRUE";
2039                         bv.bv_len = SLAP_GLUE_ADVERTISE( c->be ) ? STRLENOF("advertise") :
2040                                 STRLENOF("TRUE");
2041
2042                         value_add_one( &c->rvalue_vals, &bv );
2043                         rc = 0;
2044                 }
2045                 break;
2046         case LDAP_MOD_DELETE:
2047                 if ( !c->line  || strcasecmp( c->line, "advertise" )) {
2048                         glue_sub_del( c->be );
2049                 } else {
2050                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_GLUE_ADVERTISE;
2051                 }
2052                 rc = 0;
2053                 break;
2054         case LDAP_MOD_ADD:
2055         case SLAP_CONFIG_ADD:
2056                 advertise = ( c->argc == 2 && !strcasecmp( c->argv[1], "advertise" ));
2057                 rc = glue_sub_add( c->be, advertise, CONFIG_ONLINE_ADD( c ));
2058                 break;
2059         }
2060         return rc;
2061 }
2062
2063 static int
2064 config_suffix(ConfigArgs *c)
2065 {
2066         Backend *tbe;
2067         struct berval pdn, ndn;
2068         char    *notallowed = NULL;
2069
2070         if ( c->be == frontendDB ) {
2071                 notallowed = "frontend";
2072
2073         } else if ( SLAP_MONITOR(c->be) ) {
2074                 notallowed = "monitor";
2075
2076         } else if ( SLAP_CONFIG(c->be) ) {
2077                 notallowed = "config";
2078         }
2079
2080         if ( notallowed != NULL ) {
2081                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
2082
2083                 switch ( c->op ) {
2084                 case LDAP_MOD_ADD:
2085                 case LDAP_MOD_DELETE:
2086                 case LDAP_MOD_REPLACE:
2087                 case LDAP_MOD_INCREMENT:
2088                 case SLAP_CONFIG_ADD:
2089                         if ( !BER_BVISNULL( &c->value_dn ) ) {
2090                                 snprintf( buf, sizeof( buf ), "<%s> ",
2091                                                 c->value_dn.bv_val );
2092                         }
2093
2094                         Debug(LDAP_DEBUG_ANY,
2095                                 "%s: suffix %snot allowed in %s database.\n",
2096                                 c->log, buf, notallowed );
2097                         break;
2098
2099                 case SLAP_CONFIG_EMIT:
2100                         /* don't complain when emitting... */
2101                         break;
2102
2103                 default:
2104                         /* FIXME: don't know what values may be valid;
2105                          * please remove assertion, or add legal values
2106                          * to either block */
2107                         assert( 0 );
2108                         break;
2109                 }
2110
2111                 return 1;
2112         }
2113
2114         if (c->op == SLAP_CONFIG_EMIT) {
2115                 if ( c->be->be_suffix == NULL
2116                                 || BER_BVISNULL( &c->be->be_suffix[0] ) )
2117                 {
2118                         return 1;
2119                 } else {
2120                         value_add( &c->rvalue_vals, c->be->be_suffix );
2121                         value_add( &c->rvalue_nvals, c->be->be_nsuffix );
2122                         return 0;
2123                 }
2124         } else if ( c->op == LDAP_MOD_DELETE ) {
2125                 if ( c->valx < 0 ) {
2126                         ber_bvarray_free( c->be->be_suffix );
2127                         ber_bvarray_free( c->be->be_nsuffix );
2128                         c->be->be_suffix = NULL;
2129                         c->be->be_nsuffix = NULL;
2130                 } else {
2131                         int i = c->valx;
2132                         ch_free( c->be->be_suffix[i].bv_val );
2133                         ch_free( c->be->be_nsuffix[i].bv_val );
2134                         do {
2135                                 c->be->be_suffix[i] = c->be->be_suffix[i+1];
2136                                 c->be->be_nsuffix[i] = c->be->be_nsuffix[i+1];
2137                                 i++;
2138                         } while ( !BER_BVISNULL( &c->be->be_suffix[i] ) );
2139                 }
2140                 return 0;
2141         }
2142
2143 #ifdef SLAPD_MONITOR_DN
2144         if(!strcasecmp(c->argv[1], SLAPD_MONITOR_DN)) {
2145                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> DN is reserved for monitoring slapd",
2146                         c->argv[0] );
2147                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2148                         c->log, c->cr_msg, SLAPD_MONITOR_DN);
2149                 return(1);
2150         }
2151 #endif
2152
2153         pdn = c->value_dn;
2154         ndn = c->value_ndn;
2155         if (SLAP_DBHIDDEN( c->be ))
2156                 tbe = NULL;
2157         else
2158                 tbe = select_backend(&ndn, 0);
2159         if(tbe == c->be) {
2160                 Debug( LDAP_DEBUG_ANY, "%s: suffix already served by this backend!.\n",
2161                         c->log, 0, 0);
2162                 return 1;
2163                 free(pdn.bv_val);
2164                 free(ndn.bv_val);
2165         } else if(tbe) {
2166                 BackendDB *b2 = tbe;
2167
2168                 /* Does tbe precede be? */
2169                 while (( b2 = LDAP_STAILQ_NEXT(b2, be_next )) && b2 && b2 != c->be );
2170
2171                 if ( b2 ) {
2172                         char    *type = tbe->bd_info->bi_type;
2173
2174                         if ( overlay_is_over( tbe ) ) {
2175                                 slap_overinfo   *oi = (slap_overinfo *)tbe->bd_info->bi_private;
2176                                 type = oi->oi_orig->bi_type;
2177                         }
2178
2179                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> namingContext \"%s\" "
2180                                 "already served by a preceding %s database",
2181                                 c->argv[0], pdn.bv_val, type );
2182                         Debug(LDAP_DEBUG_ANY, "%s: %s serving namingContext \"%s\"\n",
2183                                 c->log, c->cr_msg, tbe->be_suffix[0].bv_val);
2184                         free(pdn.bv_val);
2185                         free(ndn.bv_val);
2186                         return(1);
2187                 }
2188         }
2189         if(pdn.bv_len == 0 && default_search_nbase.bv_len) {
2190                 Debug(LDAP_DEBUG_ANY, "%s: suffix DN empty and default search "
2191                         "base provided \"%s\" (assuming okay)\n",
2192                         c->log, default_search_base.bv_val, 0);
2193         }
2194         ber_bvarray_add(&c->be->be_suffix, &pdn);
2195         ber_bvarray_add(&c->be->be_nsuffix, &ndn);
2196         return(0);
2197 }
2198
2199 static int
2200 config_rootdn(ConfigArgs *c) {
2201         if (c->op == SLAP_CONFIG_EMIT) {
2202                 if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2203                         value_add_one(&c->rvalue_vals, &c->be->be_rootdn);
2204                         value_add_one(&c->rvalue_nvals, &c->be->be_rootndn);
2205                         return 0;
2206                 } else {
2207                         return 1;
2208                 }
2209         } else if ( c->op == LDAP_MOD_DELETE ) {
2210                 ch_free( c->be->be_rootdn.bv_val );
2211                 ch_free( c->be->be_rootndn.bv_val );
2212                 BER_BVZERO( &c->be->be_rootdn );
2213                 BER_BVZERO( &c->be->be_rootndn );
2214                 return 0;
2215         }
2216         if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2217                 ch_free( c->be->be_rootdn.bv_val );
2218                 ch_free( c->be->be_rootndn.bv_val );
2219         }
2220         c->be->be_rootdn = c->value_dn;
2221         c->be->be_rootndn = c->value_ndn;
2222         return(0);
2223 }
2224
2225 static int
2226 config_rootpw(ConfigArgs *c) {
2227         Backend *tbe;
2228
2229         if (c->op == SLAP_CONFIG_EMIT) {
2230                 if (!BER_BVISEMPTY(&c->be->be_rootpw)) {
2231                         /* don't copy, because "rootpw" is marked
2232                          * as CFG_BERVAL */
2233                         c->value_bv = c->be->be_rootpw;
2234                         return 0;
2235                 }
2236                 return 1;
2237         } else if ( c->op == LDAP_MOD_DELETE ) {
2238                 ch_free( c->be->be_rootpw.bv_val );
2239                 BER_BVZERO( &c->be->be_rootpw );
2240                 return 0;
2241         }
2242
2243         tbe = select_backend(&c->be->be_rootndn, 0);
2244         if(tbe != c->be) {
2245                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> can only be set when rootdn is under suffix",
2246                         c->argv[0] );
2247                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2248                         c->log, c->cr_msg, 0);
2249                 return(1);
2250         }
2251         if ( !BER_BVISNULL( &c->be->be_rootpw ))
2252                 ch_free( c->be->be_rootpw.bv_val );
2253         c->be->be_rootpw = c->value_bv;
2254         return(0);
2255 }
2256
2257 static int
2258 config_restrict(ConfigArgs *c) {
2259         slap_mask_t restrictops = 0;
2260         int i;
2261         slap_verbmasks restrictable_ops[] = {
2262                 { BER_BVC("bind"),              SLAP_RESTRICT_OP_BIND },
2263                 { BER_BVC("add"),               SLAP_RESTRICT_OP_ADD },
2264                 { BER_BVC("modify"),            SLAP_RESTRICT_OP_MODIFY },
2265                 { BER_BVC("rename"),            SLAP_RESTRICT_OP_RENAME },
2266                 { BER_BVC("modrdn"),            0 },
2267                 { BER_BVC("delete"),            SLAP_RESTRICT_OP_DELETE },
2268                 { BER_BVC("search"),            SLAP_RESTRICT_OP_SEARCH },
2269                 { BER_BVC("compare"),           SLAP_RESTRICT_OP_COMPARE },
2270                 { BER_BVC("read"),              SLAP_RESTRICT_OP_READS },
2271                 { BER_BVC("write"),             SLAP_RESTRICT_OP_WRITES },
2272                 { BER_BVC("extended"),          SLAP_RESTRICT_OP_EXTENDED },
2273                 { BER_BVC("extended=" LDAP_EXOP_START_TLS ),            SLAP_RESTRICT_EXOP_START_TLS },
2274                 { BER_BVC("extended=" LDAP_EXOP_MODIFY_PASSWD ),        SLAP_RESTRICT_EXOP_MODIFY_PASSWD },
2275                 { BER_BVC("extended=" LDAP_EXOP_X_WHO_AM_I ),           SLAP_RESTRICT_EXOP_WHOAMI },
2276                 { BER_BVC("extended=" LDAP_EXOP_X_CANCEL ),             SLAP_RESTRICT_EXOP_CANCEL },
2277                 { BER_BVC("all"),               SLAP_RESTRICT_OP_ALL },
2278                 { BER_BVNULL,   0 }
2279         };
2280
2281         if (c->op == SLAP_CONFIG_EMIT) {
2282                 return mask_to_verbs( restrictable_ops, c->be->be_restrictops,
2283                         &c->rvalue_vals );
2284         } else if ( c->op == LDAP_MOD_DELETE ) {
2285                 if ( !c->line ) {
2286                         c->be->be_restrictops = 0;
2287                 } else {
2288                         restrictops = verb_to_mask( c->line, restrictable_ops );
2289                         c->be->be_restrictops ^= restrictops;
2290                 }
2291                 return 0;
2292         }
2293         i = verbs_to_mask( c->argc, c->argv, restrictable_ops, &restrictops );
2294         if ( i ) {
2295                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown operation", c->argv[0] );
2296                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2297                         c->log, c->cr_msg, c->argv[i]);
2298                 return(1);
2299         }
2300         if ( restrictops & SLAP_RESTRICT_OP_EXTENDED )
2301                 restrictops &= ~SLAP_RESTRICT_EXOP_MASK;
2302         c->be->be_restrictops |= restrictops;
2303         return(0);
2304 }
2305
2306 static int
2307 config_allows(ConfigArgs *c) {
2308         slap_mask_t allows = 0;
2309         int i;
2310         slap_verbmasks allowable_ops[] = {
2311                 { BER_BVC("bind_v2"),           SLAP_ALLOW_BIND_V2 },
2312                 { BER_BVC("bind_anon_cred"),    SLAP_ALLOW_BIND_ANON_CRED },
2313                 { BER_BVC("bind_anon_dn"),      SLAP_ALLOW_BIND_ANON_DN },
2314                 { BER_BVC("update_anon"),       SLAP_ALLOW_UPDATE_ANON },
2315                 { BER_BVC("proxy_authz_anon"),  SLAP_ALLOW_PROXY_AUTHZ_ANON },
2316                 { BER_BVNULL,   0 }
2317         };
2318         if (c->op == SLAP_CONFIG_EMIT) {
2319                 return mask_to_verbs( allowable_ops, global_allows, &c->rvalue_vals );
2320         } else if ( c->op == LDAP_MOD_DELETE ) {
2321                 if ( !c->line ) {
2322                         global_allows = 0;
2323                 } else {
2324                         allows = verb_to_mask( c->line, allowable_ops );
2325                         global_allows ^= allows;
2326                 }
2327                 return 0;
2328         }
2329         i = verbs_to_mask(c->argc, c->argv, allowable_ops, &allows);
2330         if ( i ) {
2331                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2332                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2333                         c->log, c->cr_msg, c->argv[i]);
2334                 return(1);
2335         }
2336         global_allows |= allows;
2337         return(0);
2338 }
2339
2340 static int
2341 config_disallows(ConfigArgs *c) {
2342         slap_mask_t disallows = 0;
2343         int i;
2344         slap_verbmasks disallowable_ops[] = {
2345                 { BER_BVC("bind_anon"),         SLAP_DISALLOW_BIND_ANON },
2346                 { BER_BVC("bind_simple"),       SLAP_DISALLOW_BIND_SIMPLE },
2347                 { BER_BVC("tls_2_anon"),                SLAP_DISALLOW_TLS_2_ANON },
2348                 { BER_BVC("tls_authc"),         SLAP_DISALLOW_TLS_AUTHC },
2349                 { BER_BVNULL, 0 }
2350         };
2351         if (c->op == SLAP_CONFIG_EMIT) {
2352                 return mask_to_verbs( disallowable_ops, global_disallows, &c->rvalue_vals );
2353         } else if ( c->op == LDAP_MOD_DELETE ) {
2354                 if ( !c->line ) {
2355                         global_disallows = 0;
2356                 } else {
2357                         disallows = verb_to_mask( c->line, disallowable_ops );
2358                         global_disallows ^= disallows;
2359                 }
2360                 return 0;
2361         }
2362         i = verbs_to_mask(c->argc, c->argv, disallowable_ops, &disallows);
2363         if ( i ) {
2364                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2365                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2366                         c->log, c->cr_msg, c->argv[i]);
2367                 return(1);
2368         }
2369         global_disallows |= disallows;
2370         return(0);
2371 }
2372
2373 static int
2374 config_requires(ConfigArgs *c) {
2375         slap_mask_t requires = frontendDB->be_requires;
2376         int i, argc = c->argc;
2377         char **argv = c->argv;
2378
2379         slap_verbmasks requires_ops[] = {
2380                 { BER_BVC("bind"),              SLAP_REQUIRE_BIND },
2381                 { BER_BVC("LDAPv3"),            SLAP_REQUIRE_LDAP_V3 },
2382                 { BER_BVC("authc"),             SLAP_REQUIRE_AUTHC },
2383                 { BER_BVC("sasl"),              SLAP_REQUIRE_SASL },
2384                 { BER_BVC("strong"),            SLAP_REQUIRE_STRONG },
2385                 { BER_BVNULL, 0 }
2386         };
2387         if (c->op == SLAP_CONFIG_EMIT) {
2388                 return mask_to_verbs( requires_ops, c->be->be_requires, &c->rvalue_vals );
2389         } else if ( c->op == LDAP_MOD_DELETE ) {
2390                 if ( !c->line ) {
2391                         c->be->be_requires = 0;
2392                 } else {
2393                         requires = verb_to_mask( c->line, requires_ops );
2394                         c->be->be_requires ^= requires;
2395                 }
2396                 return 0;
2397         }
2398         /* "none" can only be first, to wipe out default/global values */
2399         if ( strcasecmp( c->argv[ 1 ], "none" ) == 0 ) {
2400                 argv++;
2401                 argc--;
2402                 requires = 0;
2403         }
2404         i = verbs_to_mask(argc, argv, requires_ops, &requires);
2405         if ( i ) {
2406                 if (strcasecmp( c->argv[ i ], "none" ) == 0 ) {
2407                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> \"none\" (#%d) must be listed first", c->argv[0], i - 1 );
2408                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2409                                 c->log, c->cr_msg, 0);
2410                 } else {
2411                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature #%d", c->argv[0], i - 1 );
2412                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2413                                 c->log, c->cr_msg, c->argv[i]);
2414                 }
2415                 return(1);
2416         }
2417         c->be->be_requires = requires;
2418         return(0);
2419 }
2420
2421 static slap_verbmasks   *loglevel_ops;
2422
2423 static int
2424 loglevel_init( void )
2425 {
2426         slap_verbmasks  lo[] = {
2427                 { BER_BVC("Any"),       -1 },
2428                 { BER_BVC("Trace"),     LDAP_DEBUG_TRACE },
2429                 { BER_BVC("Packets"),   LDAP_DEBUG_PACKETS },
2430                 { BER_BVC("Args"),      LDAP_DEBUG_ARGS },
2431                 { BER_BVC("Conns"),     LDAP_DEBUG_CONNS },
2432                 { BER_BVC("BER"),       LDAP_DEBUG_BER },
2433                 { BER_BVC("Filter"),    LDAP_DEBUG_FILTER },
2434                 { BER_BVC("Config"),    LDAP_DEBUG_CONFIG },
2435                 { BER_BVC("ACL"),       LDAP_DEBUG_ACL },
2436                 { BER_BVC("Stats"),     LDAP_DEBUG_STATS },
2437                 { BER_BVC("Stats2"),    LDAP_DEBUG_STATS2 },
2438                 { BER_BVC("Shell"),     LDAP_DEBUG_SHELL },
2439                 { BER_BVC("Parse"),     LDAP_DEBUG_PARSE },
2440 #if 0   /* no longer used (nor supported) */
2441                 { BER_BVC("Cache"),     LDAP_DEBUG_CACHE },
2442                 { BER_BVC("Index"),     LDAP_DEBUG_INDEX },
2443 #endif
2444                 { BER_BVC("Sync"),      LDAP_DEBUG_SYNC },
2445                 { BER_BVC("None"),      LDAP_DEBUG_NONE },
2446                 { BER_BVNULL,           0 }
2447         };
2448
2449         return slap_verbmasks_init( &loglevel_ops, lo );
2450 }
2451
2452 static void
2453 loglevel_destroy( void )
2454 {
2455         if ( loglevel_ops ) {
2456                 (void)slap_verbmasks_destroy( loglevel_ops );
2457         }
2458         loglevel_ops = NULL;
2459 }
2460
2461 static slap_mask_t      loglevel_ignore[] = { -1, 0 };
2462
2463 int
2464 slap_loglevel_register( slap_mask_t m, struct berval *s )
2465 {
2466         int     rc;
2467
2468         if ( loglevel_ops == NULL ) {
2469                 loglevel_init();
2470         }
2471
2472         rc = slap_verbmasks_append( &loglevel_ops, m, s, loglevel_ignore );
2473
2474         if ( rc != 0 ) {
2475                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_register(%lu, \"%s\") failed\n",
2476                         m, s->bv_val, 0 );
2477         }
2478
2479         return rc;
2480 }
2481
2482 int
2483 slap_loglevel_get( struct berval *s, int *l )
2484 {
2485         int             rc;
2486         slap_mask_t     m, i;
2487
2488         if ( loglevel_ops == NULL ) {
2489                 loglevel_init();
2490         }
2491
2492         for ( m = 0, i = 1; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2493                 m |= loglevel_ops[ i ].mask;
2494         }
2495
2496         for ( i = 1; m & i; i <<= 1 )
2497                 ;
2498
2499         if ( i == 0 ) {
2500                 return -1;
2501         }
2502
2503         rc = slap_verbmasks_append( &loglevel_ops, i, s, loglevel_ignore );
2504
2505         if ( rc != 0 ) {
2506                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_get(%lu, \"%s\") failed\n",
2507                         i, s->bv_val, 0 );
2508
2509         } else {
2510                 *l = i;
2511         }
2512
2513         return rc;
2514 }
2515
2516 int
2517 str2loglevel( const char *s, int *l )
2518 {
2519         int     i;
2520
2521         if ( loglevel_ops == NULL ) {
2522                 loglevel_init();
2523         }
2524
2525         i = verb_to_mask( s, loglevel_ops );
2526
2527         if ( BER_BVISNULL( &loglevel_ops[ i ].word ) ) {
2528                 return -1;
2529         }
2530
2531         *l = loglevel_ops[ i ].mask;
2532
2533         return 0;
2534 }
2535
2536 const char *
2537 loglevel2str( int l )
2538 {
2539         struct berval   bv = BER_BVNULL;
2540
2541         loglevel2bv( l, &bv );
2542
2543         return bv.bv_val;
2544 }
2545
2546 int
2547 loglevel2bv( int l, struct berval *bv )
2548 {
2549         if ( loglevel_ops == NULL ) {
2550                 loglevel_init();
2551         }
2552
2553         BER_BVZERO( bv );
2554
2555         return enum_to_verb( loglevel_ops, l, bv ) == -1;
2556 }
2557
2558 int
2559 loglevel2bvarray( int l, BerVarray *bva )
2560 {
2561         if ( loglevel_ops == NULL ) {
2562                 loglevel_init();
2563         }
2564
2565         return mask_to_verbs( loglevel_ops, l, bva );
2566 }
2567
2568 int
2569 loglevel_print( FILE *out )
2570 {
2571         int     i;
2572
2573         if ( loglevel_ops == NULL ) {
2574                 loglevel_init();
2575         }
2576
2577         fprintf( out, "Installed log subsystems:\n\n" );
2578         for ( i = 0; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2579                 fprintf( out, "\t%-30s (%lu)\n",
2580                         loglevel_ops[ i ].word.bv_val,
2581                         loglevel_ops[ i ].mask );
2582         }
2583
2584         fprintf( out, "\nNOTE: custom log subsystems may be later installed "
2585                 "by specific code\n\n" );
2586
2587         return 0;
2588 }
2589
2590 static int config_syslog;
2591
2592 static int
2593 config_loglevel(ConfigArgs *c) {
2594         int i;
2595
2596         if ( loglevel_ops == NULL ) {
2597                 loglevel_init();
2598         }
2599
2600         if (c->op == SLAP_CONFIG_EMIT) {
2601                 /* Get default or commandline slapd setting */
2602                 if ( ldap_syslog && !config_syslog )
2603                         config_syslog = ldap_syslog;
2604                 return loglevel2bvarray( config_syslog, &c->rvalue_vals );
2605
2606         } else if ( c->op == LDAP_MOD_DELETE ) {
2607                 if ( !c->line ) {
2608                         config_syslog = 0;
2609                 } else {
2610                         int level = verb_to_mask( c->line, loglevel_ops );
2611                         config_syslog ^= level;
2612                 }
2613                 if ( slapMode & SLAP_SERVER_MODE ) {
2614                         ldap_syslog = config_syslog;
2615                 }
2616                 return 0;
2617         }
2618
2619         for( i=1; i < c->argc; i++ ) {
2620                 int     level;
2621
2622                 if ( isdigit((unsigned char)c->argv[i][0]) || c->argv[i][0] == '-' ) {
2623                         if( lutil_atoi( &level, c->argv[i] ) != 0 ) {
2624                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse level", c->argv[0] );
2625                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2626                                         c->log, c->cr_msg, c->argv[i]);
2627                                 return( 1 );
2628                         }
2629                 } else {
2630                         if ( str2loglevel( c->argv[i], &level ) ) {
2631                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown level", c->argv[0] );
2632                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2633                                         c->log, c->cr_msg, c->argv[i]);
2634                                 return( 1 );
2635                         }
2636                 }
2637                 /* Explicitly setting a zero clears all the levels */
2638                 if ( level )
2639                         config_syslog |= level;
2640                 else
2641                         config_syslog = 0;
2642         }
2643         if ( slapMode & SLAP_SERVER_MODE ) {
2644                 ldap_syslog = config_syslog;
2645         }
2646         return(0);
2647 }
2648
2649 static int
2650 config_referral(ConfigArgs *c) {
2651         struct berval val;
2652         if (c->op == SLAP_CONFIG_EMIT) {
2653                 if ( default_referral ) {
2654                         value_add( &c->rvalue_vals, default_referral );
2655                         return 0;
2656                 } else {
2657                         return 1;
2658                 }
2659         } else if ( c->op == LDAP_MOD_DELETE ) {
2660                 if ( c->valx < 0 ) {
2661                         ber_bvarray_free( default_referral );
2662                         default_referral = NULL;
2663                 } else {
2664                         int i = c->valx;
2665                         ch_free( default_referral[i].bv_val );
2666                         for (; default_referral[i].bv_val; i++ )
2667                                 default_referral[i] = default_referral[i+1];
2668                 }
2669                 return 0;
2670         }
2671         if(validate_global_referral(c->argv[1])) {
2672                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2673                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2674                         c->log, c->cr_msg, c->argv[1]);
2675                 return(1);
2676         }
2677
2678         ber_str2bv(c->argv[1], 0, 0, &val);
2679         if(value_add_one(&default_referral, &val)) return(LDAP_OTHER);
2680         return(0);
2681 }
2682
2683 static struct {
2684         struct berval key;
2685         int off;
2686 } sec_keys[] = {
2687         { BER_BVC("ssf="), offsetof(slap_ssf_set_t, sss_ssf) },
2688         { BER_BVC("transport="), offsetof(slap_ssf_set_t, sss_transport) },
2689         { BER_BVC("tls="), offsetof(slap_ssf_set_t, sss_tls) },
2690         { BER_BVC("sasl="), offsetof(slap_ssf_set_t, sss_sasl) },
2691         { BER_BVC("update_ssf="), offsetof(slap_ssf_set_t, sss_update_ssf) },
2692         { BER_BVC("update_transport="), offsetof(slap_ssf_set_t, sss_update_transport) },
2693         { BER_BVC("update_tls="), offsetof(slap_ssf_set_t, sss_update_tls) },
2694         { BER_BVC("update_sasl="), offsetof(slap_ssf_set_t, sss_update_sasl) },
2695         { BER_BVC("simple_bind="), offsetof(slap_ssf_set_t, sss_simple_bind) },
2696         { BER_BVNULL, 0 }
2697 };
2698
2699 static int
2700 config_security(ConfigArgs *c) {
2701         slap_ssf_set_t *set = &c->be->be_ssf_set;
2702         char *next;
2703         int i, j;
2704         if (c->op == SLAP_CONFIG_EMIT) {
2705                 char numbuf[32];
2706                 struct berval bv;
2707                 slap_ssf_t *tgt;
2708                 int rc = 1;
2709
2710                 for (i=0; !BER_BVISNULL( &sec_keys[i].key ); i++) {
2711                         tgt = (slap_ssf_t *)((char *)set + sec_keys[i].off);
2712                         if ( *tgt ) {
2713                                 rc = 0;
2714                                 bv.bv_len = snprintf( numbuf, sizeof( numbuf ), "%u", *tgt );
2715                                 if ( bv.bv_len >= sizeof( numbuf ) ) {
2716                                         ber_bvarray_free_x( c->rvalue_vals, NULL );
2717                                         c->rvalue_vals = NULL;
2718                                         rc = 1;
2719                                         break;
2720                                 }
2721                                 bv.bv_len += sec_keys[i].key.bv_len;
2722                                 bv.bv_val = ch_malloc( bv.bv_len + 1);
2723                                 next = lutil_strcopy( bv.bv_val, sec_keys[i].key.bv_val );
2724                                 strcpy( next, numbuf );
2725                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2726                         }
2727                 }
2728                 return rc;
2729         }
2730         for(i = 1; i < c->argc; i++) {
2731                 slap_ssf_t *tgt = NULL;
2732                 char *src = NULL;
2733                 for ( j=0; !BER_BVISNULL( &sec_keys[j].key ); j++ ) {
2734                         if(!strncasecmp(c->argv[i], sec_keys[j].key.bv_val,
2735                                 sec_keys[j].key.bv_len)) {
2736                                 src = c->argv[i] + sec_keys[j].key.bv_len;
2737                                 tgt = (slap_ssf_t *)((char *)set + sec_keys[j].off);
2738                                 break;
2739                         }
2740                 }
2741                 if ( !tgt ) {
2742                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown factor", c->argv[0] );
2743                         Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2744                                 c->log, c->cr_msg, c->argv[i]);
2745                         return(1);
2746                 }
2747
2748                 if ( lutil_atou( tgt, src ) != 0 ) {
2749                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse factor", c->argv[0] );
2750                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2751                                 c->log, c->cr_msg, c->argv[i]);
2752                         return(1);
2753                 }
2754         }
2755         return(0);
2756 }
2757
2758 char *
2759 anlist_unparse( AttributeName *an, char *ptr, ber_len_t buflen ) {
2760         int comma = 0;
2761         char *start = ptr;
2762
2763         for (; !BER_BVISNULL( &an->an_name ); an++) {
2764                 /* if buflen == 0, assume the buffer size has been 
2765                  * already checked otherwise */
2766                 if ( buflen > 0 && buflen - ( ptr - start ) < comma + an->an_name.bv_len ) return NULL;
2767                 if ( comma ) *ptr++ = ',';
2768                 ptr = lutil_strcopy( ptr, an->an_name.bv_val );
2769                 comma = 1;
2770         }
2771         return ptr;
2772 }
2773
2774 static int
2775 config_updatedn(ConfigArgs *c) {
2776         if (c->op == SLAP_CONFIG_EMIT) {
2777                 if (!BER_BVISEMPTY(&c->be->be_update_ndn)) {
2778                         value_add_one(&c->rvalue_vals, &c->be->be_update_ndn);
2779                         value_add_one(&c->rvalue_nvals, &c->be->be_update_ndn);
2780                         return 0;
2781                 }
2782                 return 1;
2783         } else if ( c->op == LDAP_MOD_DELETE ) {
2784                 ch_free( c->be->be_update_ndn.bv_val );
2785                 BER_BVZERO( &c->be->be_update_ndn );
2786                 SLAP_DBFLAGS(c->be) ^= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SLURP_SHADOW);
2787                 return 0;
2788         }
2789         if(SLAP_SHADOW(c->be)) {
2790                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database already shadowed", c->argv[0] );
2791                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2792                         c->log, c->cr_msg, 0);
2793                 return(1);
2794         }
2795
2796         ber_memfree_x( c->value_dn.bv_val, NULL );
2797         if ( !BER_BVISNULL( &c->be->be_update_ndn ) ) {
2798                 ber_memfree_x( c->be->be_update_ndn.bv_val, NULL );
2799         }
2800         c->be->be_update_ndn = c->value_ndn;
2801         BER_BVZERO( &c->value_dn );
2802         BER_BVZERO( &c->value_ndn );
2803
2804         return config_slurp_shadow( c );
2805 }
2806
2807 int
2808 config_shadow( ConfigArgs *c, int flag )
2809 {
2810         char    *notallowed = NULL;
2811
2812         if ( c->be == frontendDB ) {
2813                 notallowed = "frontend";
2814
2815         } else if ( SLAP_MONITOR(c->be) ) {
2816                 notallowed = "monitor";
2817         }
2818
2819         if ( notallowed != NULL ) {
2820                 Debug( LDAP_DEBUG_ANY, "%s: %s database cannot be shadow.\n", c->log, notallowed, 0 );
2821                 return 1;
2822         }
2823
2824         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SINGLE_SHADOW | flag);
2825
2826         return 0;
2827 }
2828
2829 static int
2830 config_updateref(ConfigArgs *c) {
2831         struct berval val;
2832         if (c->op == SLAP_CONFIG_EMIT) {
2833                 if ( c->be->be_update_refs ) {
2834                         value_add( &c->rvalue_vals, c->be->be_update_refs );
2835                         return 0;
2836                 } else {
2837                         return 1;
2838                 }
2839         } else if ( c->op == LDAP_MOD_DELETE ) {
2840                 if ( c->valx < 0 ) {
2841                         ber_bvarray_free( c->be->be_update_refs );
2842                         c->be->be_update_refs = NULL;
2843                 } else {
2844                         int i = c->valx;
2845                         ch_free( c->be->be_update_refs[i].bv_val );
2846                         for (; c->be->be_update_refs[i].bv_val; i++)
2847                                 c->be->be_update_refs[i] = c->be->be_update_refs[i+1];
2848                 }
2849                 return 0;
2850         }
2851         if(!SLAP_SHADOW(c->be) && !c->be->be_syncinfo) {
2852                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> must appear after syncrepl or updatedn",
2853                         c->argv[0] );
2854                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2855                         c->log, c->cr_msg, 0);
2856                 return(1);
2857         }
2858
2859         if(validate_global_referral(c->argv[1])) {
2860                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2861                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2862                         c->log, c->cr_msg, c->argv[1]);
2863                 return(1);
2864         }
2865         ber_str2bv(c->argv[1], 0, 0, &val);
2866         if(value_add_one(&c->be->be_update_refs, &val)) return(LDAP_OTHER);
2867         return(0);
2868 }
2869
2870 static int
2871 config_obsolete(ConfigArgs *c) {
2872         if (c->op == SLAP_CONFIG_EMIT)
2873                 return 1;
2874
2875         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> keyword is obsolete (ignored)",
2876                 c->argv[0] );
2877         Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0);
2878         return(0);
2879 }
2880
2881 static int
2882 config_include(ConfigArgs *c) {
2883         int savelineno = c->lineno;
2884         int rc;
2885         ConfigFile *cf;
2886         ConfigFile *cfsave = cfn;
2887         ConfigFile *cf2 = NULL;
2888
2889         /* Leftover from RE23. No dynamic config for include files */
2890         if ( c->op == SLAP_CONFIG_EMIT || c->op == LDAP_MOD_DELETE )
2891                 return 1;
2892
2893         cf = ch_calloc( 1, sizeof(ConfigFile));
2894         if ( cfn->c_kids ) {
2895                 for (cf2=cfn->c_kids; cf2 && cf2->c_sibs; cf2=cf2->c_sibs) ;
2896                 cf2->c_sibs = cf;
2897         } else {
2898                 cfn->c_kids = cf;
2899         }
2900         cfn = cf;
2901         ber_str2bv( c->argv[1], 0, 1, &cf->c_file );
2902         rc = read_config_file(c->argv[1], c->depth + 1, c, config_back_cf_table);
2903         c->lineno = savelineno - 1;
2904         cfn = cfsave;
2905         if ( rc ) {
2906                 if ( cf2 ) cf2->c_sibs = NULL;
2907                 else cfn->c_kids = NULL;
2908                 ch_free( cf->c_file.bv_val );
2909                 ch_free( cf );
2910         } else {
2911                 c->private = cf;
2912         }
2913         return(rc);
2914 }
2915
2916 #ifdef HAVE_TLS
2917 static int
2918 config_tls_option(ConfigArgs *c) {
2919         int flag;
2920         LDAP *ld = slap_tls_ld;
2921         switch(c->type) {
2922         case CFG_TLS_RAND:      flag = LDAP_OPT_X_TLS_RANDOM_FILE;      ld = NULL; break;
2923         case CFG_TLS_CIPHER:    flag = LDAP_OPT_X_TLS_CIPHER_SUITE;     break;
2924         case CFG_TLS_CERT_FILE: flag = LDAP_OPT_X_TLS_CERTFILE;         break;  
2925         case CFG_TLS_CERT_KEY:  flag = LDAP_OPT_X_TLS_KEYFILE;          break;
2926         case CFG_TLS_CA_PATH:   flag = LDAP_OPT_X_TLS_CACERTDIR;        break;
2927         case CFG_TLS_CA_FILE:   flag = LDAP_OPT_X_TLS_CACERTFILE;       break;
2928         case CFG_TLS_DH_FILE:   flag = LDAP_OPT_X_TLS_DHFILE;   break;
2929 #ifdef HAVE_GNUTLS
2930         case CFG_TLS_CRL_FILE:  flag = LDAP_OPT_X_TLS_CRLFILE;  break;
2931 #endif
2932         default:                Debug(LDAP_DEBUG_ANY, "%s: "
2933                                         "unknown tls_option <0x%x>\n",
2934                                         c->log, c->type, 0);
2935                 return 1;
2936         }
2937         if (c->op == SLAP_CONFIG_EMIT) {
2938                 return ldap_pvt_tls_get_option( ld, flag, &c->value_string );
2939         } else if ( c->op == LDAP_MOD_DELETE ) {
2940                 return ldap_pvt_tls_set_option( ld, flag, NULL );
2941         }
2942         ch_free(c->value_string);
2943         return(ldap_pvt_tls_set_option(ld, flag, c->argv[1]));
2944 }
2945
2946 /* FIXME: this ought to be provided by libldap */
2947 static int
2948 config_tls_config(ConfigArgs *c) {
2949         int i, flag;
2950         switch(c->type) {
2951         case CFG_TLS_CRLCHECK:  flag = LDAP_OPT_X_TLS_CRLCHECK; break;
2952         case CFG_TLS_VERIFY:    flag = LDAP_OPT_X_TLS_REQUIRE_CERT; break;
2953         default:
2954                 Debug(LDAP_DEBUG_ANY, "%s: "
2955                                 "unknown tls_option <0x%x>\n",
2956                                 c->log, c->type, 0);
2957                 return 1;
2958         }
2959         if (c->op == SLAP_CONFIG_EMIT) {
2960                 return slap_tls_get_config( slap_tls_ld, flag, &c->value_string );
2961         } else if ( c->op == LDAP_MOD_DELETE ) {
2962                 int i = 0;
2963                 return ldap_pvt_tls_set_option( slap_tls_ld, flag, &i );
2964         }
2965         ch_free( c->value_string );
2966         if ( isdigit( (unsigned char)c->argv[1][0] ) ) {
2967                 if ( lutil_atoi( &i, c->argv[1] ) != 0 ) {
2968                         Debug(LDAP_DEBUG_ANY, "%s: "
2969                                 "unable to parse %s \"%s\"\n",
2970                                 c->log, c->argv[0], c->argv[1] );
2971                         return 1;
2972                 }
2973                 return(ldap_pvt_tls_set_option(slap_tls_ld, flag, &i));
2974         } else {
2975                 return(ldap_int_tls_config(slap_tls_ld, flag, c->argv[1]));
2976         }
2977 }
2978 #endif
2979
2980 static CfEntryInfo *
2981 config_find_base( CfEntryInfo *root, struct berval *dn, CfEntryInfo **last )
2982 {
2983         struct berval cdn;
2984         char *c;
2985
2986         if ( !root ) {
2987                 *last = NULL;
2988                 return NULL;
2989         }
2990
2991         if ( dn_match( &root->ce_entry->e_nname, dn ))
2992                 return root;
2993
2994         c = dn->bv_val+dn->bv_len;
2995         for (;*c != ',';c--);
2996
2997         while(root) {
2998                 *last = root;
2999                 for (--c;c>dn->bv_val && *c != ',';c--);
3000                 cdn.bv_val = c;
3001                 if ( *c == ',' )
3002                         cdn.bv_val++;
3003                 cdn.bv_len = dn->bv_len - (cdn.bv_val - dn->bv_val);
3004
3005                 root = root->ce_kids;
3006
3007                 for (;root;root=root->ce_sibs) {
3008                         if ( dn_match( &root->ce_entry->e_nname, &cdn )) {
3009                                 if ( cdn.bv_val == dn->bv_val ) {
3010                                         return root;
3011                                 }
3012                                 break;
3013                         }
3014                 }
3015         }
3016         return root;
3017 }
3018
3019 typedef struct setup_cookie {
3020         CfBackInfo *cfb;
3021         ConfigArgs *ca;
3022         Entry *frontend;
3023         Entry *config;
3024         int     got_frontend;
3025         int got_config;
3026 } setup_cookie;
3027
3028 static int
3029 config_ldif_resp( Operation *op, SlapReply *rs )
3030 {
3031         if ( rs->sr_type == REP_SEARCH ) {
3032                 setup_cookie *sc = op->o_callback->sc_private;
3033
3034                 sc->cfb->cb_got_ldif = 1;
3035                 /* Does the frontend exist? */
3036                 if ( !sc->got_frontend ) {
3037                         if ( !strncmp( rs->sr_entry->e_nname.bv_val,
3038                                 "olcDatabase", STRLENOF( "olcDatabase" ))) {
3039                                 if ( strncmp( rs->sr_entry->e_nname.bv_val +
3040                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
3041                                         STRLENOF( "={-1}frontend" ))) {
3042                                         struct berval rdn;
3043                                         int i = op->o_noop;
3044                                         sc->ca->be = frontendDB;
3045                                         sc->ca->bi = frontendDB->bd_info;
3046                                         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
3047                                         rdn.bv_val = sc->ca->log;
3048                                         rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3049                                                 "%s=" SLAP_X_ORDERED_FMT "%s",
3050                                                 cfAd_database->ad_cname.bv_val, -1,
3051                                                 sc->ca->bi->bi_type);
3052                                         op->o_noop = 1;
3053                                         sc->frontend = config_build_entry( op, rs,
3054                                                 sc->cfb->cb_root, sc->ca, &rdn, &CFOC_DATABASE,
3055                                                 sc->ca->be->be_cf_ocs );
3056                                         op->o_noop = i;
3057                                         sc->got_frontend++;
3058                                 } else {
3059                                         sc->got_frontend++;
3060                                         goto ok;
3061                                 }
3062                         }
3063                 }
3064                 /* Does the configDB exist? */
3065                 if ( sc->got_frontend && !sc->got_config &&
3066                         !strncmp( rs->sr_entry->e_nname.bv_val,
3067                         "olcDatabase", STRLENOF( "olcDatabase" ))) {
3068                         if ( strncmp( rs->sr_entry->e_nname.bv_val +
3069                                 STRLENOF( "olcDatabase" ), "={0}config",
3070                                 STRLENOF( "={0}config" ))) {
3071                                 struct berval rdn;
3072                                 int i = op->o_noop;
3073                                 sc->ca->be = LDAP_STAILQ_FIRST( &backendDB );
3074                                 sc->ca->bi = sc->ca->be->bd_info;
3075                                 rdn.bv_val = sc->ca->log;
3076                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3077                                         "%s=" SLAP_X_ORDERED_FMT "%s",
3078                                         cfAd_database->ad_cname.bv_val, 0,
3079                                         sc->ca->bi->bi_type);
3080                                 op->o_noop = 1;
3081                                 sc->config = config_build_entry( op, rs, sc->cfb->cb_root,
3082                                         sc->ca, &rdn, &CFOC_DATABASE, sc->ca->be->be_cf_ocs );
3083                                 op->o_noop = i;
3084                         }
3085                         sc->got_config++;
3086                 }
3087
3088 ok:
3089                 rs->sr_err = config_add_internal( sc->cfb, rs->sr_entry, sc->ca, NULL, NULL, NULL );
3090                 if ( rs->sr_err != LDAP_SUCCESS ) {
3091                         Debug( LDAP_DEBUG_ANY, "config error processing %s: %s\n",
3092                                 rs->sr_entry->e_name.bv_val, sc->ca->cr_msg, 0 );
3093                 }
3094         }
3095         return rs->sr_err;
3096 }
3097
3098 /* Configure and read the underlying back-ldif store */
3099 static int
3100 config_setup_ldif( BackendDB *be, const char *dir, int readit ) {
3101         CfBackInfo *cfb = be->be_private;
3102         ConfigArgs c = {0};
3103         ConfigTable *ct;
3104         char *argv[3];
3105         int rc = 0;
3106         setup_cookie sc;
3107         slap_callback cb = { NULL, config_ldif_resp, NULL, NULL };
3108         Connection conn = {0};
3109         OperationBuffer opbuf;
3110         Operation *op;
3111         SlapReply rs = {REP_RESULT};
3112         Filter filter = { LDAP_FILTER_PRESENT };
3113         struct berval filterstr = BER_BVC("(objectclass=*)");
3114         struct stat st;
3115
3116         /* Is the config directory available? */
3117         if ( stat( dir, &st ) < 0 ) {
3118                 /* No, so don't bother using the backing store.
3119                  * All changes will be in-memory only.
3120                  */
3121                 return 0;
3122         }
3123                 
3124         cfb->cb_db.bd_info = backend_info( "ldif" );
3125         if ( !cfb->cb_db.bd_info )
3126                 return 0;       /* FIXME: eventually this will be a fatal error */
3127
3128         if ( backend_db_init( "ldif", &cfb->cb_db, -1, NULL ) == NULL )
3129                 return 1;
3130
3131         cfb->cb_db.be_suffix = be->be_suffix;
3132         cfb->cb_db.be_nsuffix = be->be_nsuffix;
3133
3134         /* The suffix is always "cn=config". The underlying DB's rootdn
3135          * is always the same as the suffix.
3136          */
3137         cfb->cb_db.be_rootdn = be->be_suffix[0];
3138         cfb->cb_db.be_rootndn = be->be_nsuffix[0];
3139
3140         ber_str2bv( dir, 0, 1, &cfdir );
3141
3142         c.be = &cfb->cb_db;
3143         c.fname = "slapd";
3144         c.argc = 2;
3145         argv[0] = "directory";
3146         argv[1] = (char *)dir;
3147         argv[2] = NULL;
3148         c.argv = argv;
3149         c.reply.err = 0;
3150         c.reply.msg[0] = 0;
3151         c.table = Cft_Database;
3152
3153         ct = config_find_keyword( c.be->be_cf_ocs->co_table, &c );
3154         if ( !ct )
3155                 return 1;
3156
3157         if ( config_add_vals( ct, &c ))
3158                 return 1;
3159
3160         if ( backend_startup_one( &cfb->cb_db, &c.reply ))
3161                 return 1;
3162
3163         if ( readit ) {
3164                 void *thrctx = ldap_pvt_thread_pool_context();
3165                 int prev_DN_strict;
3166
3167                 connection_fake_init( &conn, &opbuf, thrctx );
3168                 op = &opbuf.ob_op;
3169
3170                 filter.f_desc = slap_schema.si_ad_objectClass;
3171
3172                 op->o_tag = LDAP_REQ_SEARCH;
3173
3174                 op->ors_filter = &filter;
3175                 op->ors_filterstr = filterstr;
3176                 op->ors_scope = LDAP_SCOPE_SUBTREE;
3177
3178                 op->o_dn = c.be->be_rootdn;
3179                 op->o_ndn = c.be->be_rootndn;
3180
3181                 op->o_req_dn = be->be_suffix[0];
3182                 op->o_req_ndn = be->be_nsuffix[0];
3183
3184                 op->ors_tlimit = SLAP_NO_LIMIT;
3185                 op->ors_slimit = SLAP_NO_LIMIT;
3186
3187                 op->ors_attrs = slap_anlist_all_attributes;
3188                 op->ors_attrsonly = 0;
3189
3190                 op->o_callback = &cb;
3191                 sc.cfb = cfb;
3192                 sc.ca = &c;
3193                 cb.sc_private = &sc;
3194                 sc.got_frontend = 0;
3195                 sc.got_config = 0;
3196                 sc.frontend = NULL;
3197                 sc.config = NULL;
3198
3199                 op->o_bd = &cfb->cb_db;
3200                 
3201                 /* Allow unknown attrs in DNs */
3202                 prev_DN_strict = slap_DN_strict;
3203                 slap_DN_strict = 0;
3204
3205                 rc = op->o_bd->be_search( op, &rs );
3206
3207                 /* Restore normal DN validation */
3208                 slap_DN_strict = prev_DN_strict;
3209
3210                 op->o_tag = LDAP_REQ_ADD;
3211                 if ( rc == LDAP_SUCCESS && sc.frontend ) {
3212                         op->ora_e = sc.frontend;
3213                         rc = op->o_bd->be_add( op, &rs );
3214                 }
3215                 if ( rc == LDAP_SUCCESS && sc.config ) {
3216                         op->ora_e = sc.config;
3217                         rc = op->o_bd->be_add( op, &rs );
3218                 }
3219                 ldap_pvt_thread_pool_context_reset( thrctx );
3220         }
3221
3222         /* ITS#4194 - only use if it's present, or we're converting. */
3223         if ( !readit || rc == LDAP_SUCCESS )
3224                 cfb->cb_use_ldif = 1;
3225
3226         return rc;
3227 }
3228
3229 static int
3230 CfOc_cmp( const void *c1, const void *c2 ) {
3231         const ConfigOCs *co1 = c1;
3232         const ConfigOCs *co2 = c2;
3233
3234         return ber_bvcmp( co1->co_name, co2->co_name );
3235 }
3236
3237 int
3238 config_register_schema(ConfigTable *ct, ConfigOCs *ocs) {
3239         int i;
3240
3241         i = init_config_attrs( ct );
3242         if ( i ) return i;
3243
3244         /* set up the objectclasses */
3245         i = init_config_ocs( ocs );
3246         if ( i ) return i;
3247
3248         for (i=0; ocs[i].co_def; i++) {
3249                 if ( ocs[i].co_oc ) {
3250                         ocs[i].co_name = &ocs[i].co_oc->soc_cname;
3251                         if ( !ocs[i].co_table )
3252                                 ocs[i].co_table = ct;
3253                         avl_insert( &CfOcTree, &ocs[i], CfOc_cmp, avl_dup_error );
3254                 }
3255         }
3256         return 0;
3257 }
3258
3259 int
3260 read_config(const char *fname, const char *dir) {
3261         BackendDB *be;
3262         CfBackInfo *cfb;
3263         const char *cfdir, *cfname;
3264         int rc;
3265
3266         /* Setup the config backend */
3267         be = backend_db_init( "config", NULL, 0, NULL );
3268         if ( !be )
3269                 return 1;
3270
3271         cfb = be->be_private;
3272         be->be_dfltaccess = ACL_NONE;
3273
3274         /* If no .conf, or a dir was specified, setup the dir */
3275         if ( !fname || dir ) {
3276                 if ( dir ) {
3277                         /* If explicitly given, check for existence */
3278                         struct stat st;
3279
3280                         if ( stat( dir, &st ) < 0 ) {
3281                                 Debug( LDAP_DEBUG_ANY,
3282                                         "invalid config directory %s, error %d\n",
3283                                                 dir, errno, 0 );
3284                                 return 1;
3285                         }
3286                         cfdir = dir;
3287                 } else {
3288                         cfdir = SLAPD_DEFAULT_CONFIGDIR;
3289                 }
3290                 /* if fname is defaulted, try reading .d */
3291                 rc = config_setup_ldif( be, cfdir, !fname );
3292
3293                 if ( rc ) {
3294                         /* It may be OK if the base object doesn't exist yet. */
3295                         if ( rc != LDAP_NO_SUCH_OBJECT )
3296                                 return 1;
3297                         /* ITS#4194: But if dir was specified and no fname,
3298                          * then we were supposed to read the dir. Unless we're
3299                          * trying to slapadd the dir...
3300                          */
3301                         if ( dir && !fname ) {
3302                                 if ( slapMode & (SLAP_SERVER_MODE|SLAP_TOOL_READMAIN|SLAP_TOOL_READONLY))
3303                                         return 1;
3304                                 /* Assume it's slapadd with a config dir, let it continue */
3305                                 rc = 0;
3306                                 cfb->cb_got_ldif = 1;
3307                                 cfb->cb_use_ldif = 1;
3308                                 goto done;
3309                         }
3310                 }
3311
3312                 /* If we read the config from back-ldif, nothing to do here */
3313                 if ( cfb->cb_got_ldif ) {
3314                         rc = 0;
3315                         goto done;
3316                 }
3317         }
3318
3319         if ( fname )
3320                 cfname = fname;
3321         else
3322                 cfname = SLAPD_DEFAULT_CONFIGFILE;
3323
3324         rc = read_config_file(cfname, 0, NULL, config_back_cf_table);
3325
3326         if ( rc == 0 )
3327                 ber_str2bv( cfname, 0, 1, &cfb->cb_config->c_file );
3328
3329 done:
3330         if ( rc == 0 && BER_BVISNULL( &frontendDB->be_schemadn ) ) {
3331                 ber_str2bv( SLAPD_SCHEMA_DN, STRLENOF( SLAPD_SCHEMA_DN ), 1,
3332                         &frontendDB->be_schemadn );
3333                 rc = dnNormalize( 0, NULL, NULL, &frontendDB->be_schemadn, &frontendDB->be_schemandn, NULL );
3334                 if ( rc != LDAP_SUCCESS ) {
3335                         Debug(LDAP_DEBUG_ANY, "read_config: "
3336                                 "unable to normalize default schema DN \"%s\"\n",
3337                                 frontendDB->be_schemadn.bv_val, 0, 0 );
3338                         /* must not happen */
3339                         assert( 0 );
3340                 }
3341         }
3342         return rc;
3343 }
3344
3345 static int
3346 config_back_bind( Operation *op, SlapReply *rs )
3347 {
3348         if ( be_isroot_pw( op ) ) {
3349                 ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ));
3350                 /* frontend sends result */
3351                 return LDAP_SUCCESS;
3352         }
3353
3354         rs->sr_err = LDAP_INVALID_CREDENTIALS;
3355         send_ldap_result( op, rs );
3356
3357         return rs->sr_err;
3358 }
3359
3360 static int
3361 config_send( Operation *op, SlapReply *rs, CfEntryInfo *ce, int depth )
3362 {
3363         int rc = 0;
3364
3365         if ( test_filter( op, ce->ce_entry, op->ors_filter ) == LDAP_COMPARE_TRUE )
3366         {
3367                 rs->sr_attrs = op->ors_attrs;
3368                 rs->sr_entry = ce->ce_entry;
3369                 rs->sr_flags = 0;
3370                 rc = send_search_entry( op, rs );
3371         }
3372         if ( op->ors_scope == LDAP_SCOPE_SUBTREE ) {
3373                 if ( ce->ce_kids ) {
3374                         rc = config_send( op, rs, ce->ce_kids, 1 );
3375                         if ( rc ) return rc;
3376                 }
3377                 if ( depth ) {
3378                         for (ce=ce->ce_sibs; ce; ce=ce->ce_sibs) {
3379                                 rc = config_send( op, rs, ce, 0 );
3380                                 if ( rc ) break;
3381                         }
3382                 }
3383         }
3384         return rc;
3385 }
3386
3387 static ConfigTable *
3388 config_find_table( ConfigOCs **colst, int nocs, AttributeDescription *ad,
3389         ConfigArgs *ca )
3390 {
3391         int i, j;
3392
3393         for (j=0; j<nocs; j++) {
3394                 for (i=0; colst[j]->co_table[i].name; i++)
3395                         if ( colst[j]->co_table[i].ad == ad ) {
3396                                 ca->table = colst[j]->co_type;
3397                                 return &colst[j]->co_table[i];
3398                         }
3399         }
3400         return NULL;
3401 }
3402
3403 /* Sort the attributes of the entry according to the order defined
3404  * in the objectclass, with required attributes occurring before
3405  * allowed attributes. For any attributes with sequencing dependencies
3406  * (e.g., rootDN must be defined after suffix) the objectclass must
3407  * list the attributes in the desired sequence.
3408  */
3409 static void
3410 sort_attrs( Entry *e, ConfigOCs **colst, int nocs )
3411 {
3412         Attribute *a, *head = NULL, *tail = NULL, **prev;
3413         int i, j;
3414
3415         for (i=0; i<nocs; i++) {
3416                 if ( colst[i]->co_oc->soc_required ) {
3417                         AttributeType **at = colst[i]->co_oc->soc_required;
3418                         for (j=0; at[j]; j++) {
3419                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3420                                         prev = &(*prev)->a_next, a=a->a_next) {
3421                                         if ( a->a_desc == at[j]->sat_ad ) {
3422                                                 *prev = a->a_next;
3423                                                 if (!head) {
3424                                                         head = a;
3425                                                         tail = a;
3426                                                 } else {
3427                                                         tail->a_next = a;
3428                                                         tail = a;
3429                                                 }
3430                                                 break;
3431                                         }
3432                                 }
3433                         }
3434                 }
3435                 if ( colst[i]->co_oc->soc_allowed ) {
3436                         AttributeType **at = colst[i]->co_oc->soc_allowed;
3437                         for (j=0; at[j]; j++) {
3438                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3439                                         prev = &(*prev)->a_next, a=a->a_next) {
3440                                         if ( a->a_desc == at[j]->sat_ad ) {
3441                                                 *prev = a->a_next;
3442                                                 if (!head) {
3443                                                         head = a;
3444                                                         tail = a;
3445                                                 } else {
3446                                                         tail->a_next = a;
3447                                                         tail = a;
3448                                                 }
3449                                                 break;
3450                                         }
3451                                 }
3452                         }
3453                 }
3454         }
3455         if ( tail ) {
3456                 tail->a_next = e->e_attrs;
3457                 e->e_attrs = head;
3458         }
3459 }
3460
3461 static int
3462 check_vals( ConfigTable *ct, ConfigArgs *ca, void *ptr, int isAttr )
3463 {
3464         Attribute *a = NULL;
3465         AttributeDescription *ad;
3466         BerVarray vals;
3467
3468         int i, rc = 0;
3469
3470         if ( isAttr ) {
3471                 a = ptr;
3472                 ad = a->a_desc;
3473                 vals = a->a_vals;
3474         } else {
3475                 Modifications *ml = ptr;
3476                 ad = ml->sml_desc;
3477                 vals = ml->sml_values;
3478         }
3479
3480         if ( a && ( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL )) {
3481                 rc = ordered_value_sort( a, 1 );
3482                 if ( rc ) {
3483                         snprintf(ca->cr_msg, sizeof( ca->cr_msg ), "ordered_value_sort failed on attr %s\n",
3484                                 ad->ad_cname.bv_val );
3485                         return rc;
3486                 }
3487         }
3488         for ( i=0; vals[i].bv_val; i++ ) {
3489                 ca->line = vals[i].bv_val;
3490                 if (( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL ) &&
3491                         ca->line[0] == '{' ) {
3492                         char *idx = strchr( ca->line, '}' );
3493                         if ( idx ) ca->line = idx+1;
3494                 }
3495                 rc = config_parse_vals( ct, ca, i );
3496                 if ( rc ) {
3497                         break;
3498                 }
3499         }
3500         return rc;
3501 }
3502
3503 static int
3504 config_rename_attr( SlapReply *rs, Entry *e, struct berval *rdn,
3505         Attribute **at )
3506 {
3507         struct berval rtype, rval;
3508         Attribute *a;
3509         AttributeDescription *ad = NULL;
3510
3511         dnRdn( &e->e_name, rdn );
3512         rval.bv_val = strchr(rdn->bv_val, '=' ) + 1;
3513         rval.bv_len = rdn->bv_len - (rval.bv_val - rdn->bv_val);
3514         rtype.bv_val = rdn->bv_val;
3515         rtype.bv_len = rval.bv_val - rtype.bv_val - 1;
3516
3517         /* Find attr */
3518         slap_bv2ad( &rtype, &ad, &rs->sr_text );
3519         a = attr_find( e->e_attrs, ad );
3520         if (!a ) return LDAP_NAMING_VIOLATION;
3521         *at = a;
3522
3523         return 0;
3524 }
3525
3526 static void
3527 config_rename_kids( CfEntryInfo *ce )
3528 {
3529         CfEntryInfo *ce2;
3530         struct berval rdn, nrdn;
3531
3532         for (ce2 = ce->ce_kids; ce2; ce2 = ce2->ce_sibs) {
3533                 dnRdn ( &ce2->ce_entry->e_name, &rdn );
3534                 dnRdn ( &ce2->ce_entry->e_nname, &nrdn );
3535                 free( ce2->ce_entry->e_name.bv_val );
3536                 free( ce2->ce_entry->e_nname.bv_val );
3537                 build_new_dn( &ce2->ce_entry->e_name, &ce->ce_entry->e_name,
3538                         &rdn, NULL );
3539                 build_new_dn( &ce2->ce_entry->e_nname, &ce->ce_entry->e_nname,
3540                         &nrdn, NULL );
3541                 config_rename_kids( ce2 );
3542         }
3543 }
3544
3545 static int
3546 config_rename_one( Operation *op, SlapReply *rs, Entry *e,
3547         CfEntryInfo *parent, Attribute *a, struct berval *newrdn,
3548         struct berval *nnewrdn, int use_ldif )
3549 {
3550         char *ptr1;
3551         int rc = 0;
3552         struct berval odn, ondn;
3553
3554         odn = e->e_name;
3555         ondn = e->e_nname;
3556         build_new_dn( &e->e_name, &parent->ce_entry->e_name, newrdn, NULL );
3557         build_new_dn( &e->e_nname, &parent->ce_entry->e_nname, nnewrdn, NULL );
3558
3559         /* Replace attr */
3560         free( a->a_vals[0].bv_val );
3561         ptr1 = strchr( newrdn->bv_val, '=' ) + 1;
3562         a->a_vals[0].bv_len = newrdn->bv_len - (ptr1 - newrdn->bv_val);
3563         a->a_vals[0].bv_val = ch_malloc( a->a_vals[0].bv_len + 1 );
3564         strcpy( a->a_vals[0].bv_val, ptr1 );
3565
3566         if ( a->a_nvals != a->a_vals ) {
3567                 free( a->a_nvals[0].bv_val );
3568                 ptr1 = strchr( nnewrdn->bv_val, '=' ) + 1;
3569                 a->a_nvals[0].bv_len = nnewrdn->bv_len - (ptr1 - nnewrdn->bv_val);
3570                 a->a_nvals[0].bv_val = ch_malloc( a->a_nvals[0].bv_len + 1 );
3571                 strcpy( a->a_nvals[0].bv_val, ptr1 );
3572         }
3573         if ( use_ldif ) {
3574                 CfBackInfo *cfb = (CfBackInfo *)op->o_bd->be_private;
3575                 BackendDB *be = op->o_bd;
3576                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
3577                 struct berval dn, ndn, xdn, xndn;
3578
3579                 op->o_bd = &cfb->cb_db;
3580
3581                 /* Save current rootdn; use the underlying DB's rootdn */
3582                 dn = op->o_dn;
3583                 ndn = op->o_ndn;
3584                 xdn = op->o_req_dn;
3585                 xndn = op->o_req_ndn;
3586                 op->o_dn = op->o_bd->be_rootdn;
3587                 op->o_ndn = op->o_bd->be_rootndn;
3588                 op->o_req_dn = odn;
3589                 op->o_req_ndn = ondn;
3590
3591                 scp = op->o_callback;
3592                 op->o_callback = &sc;
3593                 op->orr_newrdn = *newrdn;
3594                 op->orr_nnewrdn = *nnewrdn;
3595                 op->orr_newSup = NULL;
3596                 op->orr_nnewSup = NULL;
3597                 op->orr_deleteoldrdn = 1;
3598                 op->orr_modlist = NULL;
3599                 slap_modrdn2mods( op, rs );
3600                 slap_mods_opattrs( op, &op->orr_modlist, 1 );
3601                 rc = op->o_bd->be_modrdn( op, rs );
3602                 slap_mods_free( op->orr_modlist, 1 );
3603
3604                 op->o_bd = be;
3605                 op->o_callback = scp;
3606                 op->o_dn = dn;
3607                 op->o_ndn = ndn;
3608                 op->o_req_dn = xdn;
3609                 op->o_req_ndn = xndn;
3610         }
3611         free( odn.bv_val );
3612         free( ondn.bv_val );
3613         if ( e->e_private )
3614                 config_rename_kids( e->e_private );
3615         return rc;
3616 }
3617
3618 static int
3619 config_renumber_one( Operation *op, SlapReply *rs, CfEntryInfo *parent, 
3620         Entry *e, int idx, int tailindex, int use_ldif )
3621 {
3622         struct berval ival, newrdn, nnewrdn;
3623         struct berval rdn;
3624         Attribute *a;
3625         char ibuf[32], *ptr1, *ptr2 = NULL;
3626         int rc = 0;
3627
3628         rc = config_rename_attr( rs, e, &rdn, &a );
3629         if ( rc ) return rc;
3630
3631         ival.bv_val = ibuf;
3632         ival.bv_len = snprintf( ibuf, sizeof( ibuf ), SLAP_X_ORDERED_FMT, idx );
3633         if ( ival.bv_len >= sizeof( ibuf ) ) {
3634                 return LDAP_NAMING_VIOLATION;
3635         }
3636         
3637         newrdn.bv_len = rdn.bv_len + ival.bv_len;
3638         newrdn.bv_val = ch_malloc( newrdn.bv_len+1 );
3639
3640         if ( tailindex ) {
3641                 ptr1 = lutil_strncopy( newrdn.bv_val, rdn.bv_val, rdn.bv_len );
3642                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3643         } else {
3644                 int xlen;
3645                 ptr2 = ber_bvchr( &rdn, '}' );
3646                 if ( ptr2 ) {
3647                         ptr2++;
3648                 } else {
3649                         ptr2 = rdn.bv_val + a->a_desc->ad_cname.bv_len + 1;
3650                 }
3651                 xlen = rdn.bv_len - (ptr2 - rdn.bv_val);
3652                 ptr1 = lutil_strncopy( newrdn.bv_val, a->a_desc->ad_cname.bv_val,
3653                         a->a_desc->ad_cname.bv_len );
3654                 *ptr1++ = '=';
3655                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3656                 ptr1 = lutil_strncopy( ptr1, ptr2, xlen );
3657                 *ptr1 = '\0';
3658         }
3659
3660         /* Do the equivalent of ModRDN */
3661         /* Replace DN / NDN */
3662         newrdn.bv_len = ptr1 - newrdn.bv_val;
3663         rdnNormalize( 0, NULL, NULL, &newrdn, &nnewrdn, NULL );
3664         rc = config_rename_one( op, rs, e, parent, a, &newrdn, &nnewrdn, use_ldif );
3665
3666         free( nnewrdn.bv_val );
3667         free( newrdn.bv_val );
3668         return rc;
3669 }
3670
3671 static int
3672 check_name_index( CfEntryInfo *parent, ConfigType ce_type, Entry *e,
3673         SlapReply *rs, int *renum, int *ibase )
3674 {
3675         CfEntryInfo *ce;
3676         int index = -1, gotindex = 0, nsibs, rc = 0;
3677         int renumber = 0, tailindex = 0, isfrontend = 0, isconfig = 0;
3678         char *ptr1, *ptr2 = NULL;
3679         struct berval rdn;
3680
3681         if ( renum ) *renum = 0;
3682
3683         /* These entries don't get indexed/renumbered */
3684         if ( ce_type == Cft_Global ) return 0;
3685         if ( ce_type == Cft_Schema && parent->ce_type == Cft_Global ) return 0;
3686
3687         if ( ce_type == Cft_Module )
3688                 tailindex = 1;
3689
3690         /* See if the rdn has an index already */
3691         dnRdn( &e->e_name, &rdn );
3692         if ( ce_type == Cft_Database ) {
3693                 if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("frontend"),
3694                                 "frontend", STRLENOF("frontend") )) 
3695                         isfrontend = 1;
3696                 else if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("config"),
3697                                 "config", STRLENOF("config") )) 
3698                         isconfig = 1;
3699         }
3700         ptr1 = ber_bvchr( &e->e_name, '{' );
3701         if ( ptr1 && ptr1 - e->e_name.bv_val < rdn.bv_len ) {
3702                 char    *next;
3703                 ptr2 = strchr( ptr1, '}' );
3704                 if (!ptr2 || ptr2 - e->e_name.bv_val > rdn.bv_len)
3705                         return LDAP_NAMING_VIOLATION;
3706                 if ( ptr2-ptr1 == 1)
3707                         return LDAP_NAMING_VIOLATION;
3708                 gotindex = 1;
3709                 index = strtol( ptr1 + 1, &next, 10 );
3710                 if ( next == ptr1 + 1 || next[ 0 ] != '}' ) {
3711                         return LDAP_NAMING_VIOLATION;
3712                 }
3713                 if ( index < 0 ) {
3714                         /* Special case, we allow -1 for the frontendDB */
3715                         if ( index != -1 || !isfrontend )
3716                                 return LDAP_NAMING_VIOLATION;
3717                 }
3718                 if ( isconfig && index != 0 ){
3719                         return LDAP_NAMING_VIOLATION;
3720                 }
3721         }
3722
3723         /* count related kids */
3724         for (nsibs=0, ce=parent->ce_kids; ce; ce=ce->ce_sibs) {
3725                 if ( ce->ce_type == ce_type ) nsibs++;
3726         }
3727
3728         /* account for -1 frontend */
3729         if ( ce_type == Cft_Database )
3730                 nsibs--;
3731
3732         if ( index != nsibs ) {
3733                 if ( gotindex ) {
3734                         if ( index < nsibs ) {
3735                                 if ( tailindex ) return LDAP_NAMING_VIOLATION;
3736                                 /* Siblings need to be renumbered */
3737                                 if ( index != -1 || !isfrontend )
3738                                         renumber = 1;
3739                         }
3740                 }
3741                 /* config DB is always "0" */
3742                 if ( isconfig && index == -1 ) {
3743                         index = 0;
3744                 }
3745                 if ( !isfrontend && index == -1 ) {
3746                         index = nsibs;
3747                 }
3748
3749                 /* just make index = nsibs */
3750                 if ( !renumber ) {
3751                         rc = config_renumber_one( NULL, rs, parent, e, index, tailindex, 0 );
3752                 }
3753         }
3754         if ( ibase ) *ibase = index;
3755         if ( renum ) *renum = renumber;
3756         return rc;
3757 }
3758
3759 static int
3760 count_oc( ObjectClass *oc, ConfigOCs ***copp, int *nocs )
3761 {
3762         ConfigOCs       co, *cop;
3763         ObjectClass     **sups;
3764
3765         co.co_name = &oc->soc_cname;
3766         cop = avl_find( CfOcTree, &co, CfOc_cmp );
3767         if ( cop ) {
3768                 int     i;
3769
3770                 /* check for duplicates */
3771                 for ( i = 0; i < *nocs; i++ ) {
3772                         if ( *copp && (*copp)[i] == cop ) {
3773                                 break;
3774                         }
3775                 }
3776
3777                 if ( i == *nocs ) {
3778                         ConfigOCs **tmp = ch_realloc( *copp, (*nocs + 1)*sizeof( ConfigOCs * ) );
3779                         if ( tmp == NULL ) {
3780                                 return -1;
3781                         }
3782                         *copp = tmp;
3783                         (*copp)[*nocs] = cop;
3784                         (*nocs)++;
3785                 }
3786         }
3787
3788         for ( sups = oc->soc_sups; sups && *sups; sups++ ) {
3789                 if ( count_oc( *sups, copp, nocs ) ) {
3790                         return -1;
3791                 }
3792         }
3793
3794         return 0;
3795 }
3796
3797 static ConfigOCs **
3798 count_ocs( Attribute *oc_at, int *nocs )
3799 {
3800         int             i;
3801         ConfigOCs       **colst = NULL;
3802
3803         *nocs = 0;
3804
3805         for ( i = 0; !BER_BVISNULL( &oc_at->a_nvals[i] ); i++ )
3806                 /* count attrs */ ;
3807
3808         for ( ; i--; ) {
3809                 ObjectClass     *oc = oc_bvfind( &oc_at->a_nvals[i] );
3810
3811                 assert( oc != NULL );
3812                 if ( count_oc( oc, &colst, nocs ) ) {
3813                         ch_free( colst );
3814                         return NULL;
3815                 }
3816         }
3817
3818         return colst;
3819 }
3820
3821 static int
3822 cfAddInclude( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3823 {
3824         /* Leftover from RE23. Never parse this entry */
3825         return LDAP_COMPARE_TRUE;
3826 }
3827
3828 static int
3829 cfAddSchema( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3830 {
3831         ConfigFile *cfo;
3832
3833         /* This entry is hardcoded, don't re-parse it */
3834         if ( p->ce_type == Cft_Global ) {
3835                 cfn = p->ce_private;
3836                 ca->private = cfn;
3837                 return LDAP_COMPARE_TRUE;
3838         }
3839         if ( p->ce_type != Cft_Schema )
3840                 return LDAP_CONSTRAINT_VIOLATION;
3841
3842         cfn = ch_calloc( 1, sizeof(ConfigFile) );
3843         ca->private = cfn;
3844         cfo = p->ce_private;
3845         cfn->c_sibs = cfo->c_kids;
3846         cfo->c_kids = cfn;
3847         return LDAP_SUCCESS;
3848 }
3849
3850 static int
3851 cfAddDatabase( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3852 {
3853         if ( p->ce_type != Cft_Global ) {
3854                 return LDAP_CONSTRAINT_VIOLATION;
3855         }
3856         ca->be = frontendDB;    /* just to get past check_vals */
3857         return LDAP_SUCCESS;
3858 }
3859
3860 static int
3861 cfAddBackend( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3862 {
3863         if ( p->ce_type != Cft_Global ) {
3864                 return LDAP_CONSTRAINT_VIOLATION;
3865         }
3866         return LDAP_SUCCESS;
3867 }
3868
3869 static int
3870 cfAddModule( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3871 {
3872         if ( p->ce_type != Cft_Global ) {
3873                 return LDAP_CONSTRAINT_VIOLATION;
3874         }
3875         return LDAP_SUCCESS;
3876 }
3877
3878 static int
3879 cfAddOverlay( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3880 {
3881         if ( p->ce_type != Cft_Database ) {
3882                 return LDAP_CONSTRAINT_VIOLATION;
3883         }
3884         ca->be = p->ce_be;
3885         return LDAP_SUCCESS;
3886 }
3887
3888 static void
3889 schema_destroy_one( ConfigArgs *ca, ConfigOCs **colst, int nocs,
3890         CfEntryInfo *p )
3891 {
3892         ConfigTable *ct;
3893         ConfigFile *cfo;
3894         AttributeDescription *ad;
3895         const char *text;
3896
3897         ca->valx = -1;
3898         ca->line = NULL;
3899         if ( cfn->c_cr_head ) {
3900                 struct berval bv = BER_BVC("olcDitContentRules");
3901                 ad = NULL;
3902                 slap_bv2ad( &bv, &ad, &text );
3903                 ct = config_find_table( colst, nocs, ad, ca );
3904                 config_del_vals( ct, ca );
3905         }
3906         if ( cfn->c_oc_head ) {
3907                 struct berval bv = BER_BVC("olcObjectClasses");
3908                 ad = NULL;
3909                 slap_bv2ad( &bv, &ad, &text );
3910                 ct = config_find_table( colst, nocs, ad, ca );
3911                 config_del_vals( ct, ca );
3912         }
3913         if ( cfn->c_at_head ) {
3914                 struct berval bv = BER_BVC("olcAttributeTypes");
3915                 ad = NULL;
3916                 slap_bv2ad( &bv, &ad, &text );
3917                 ct = config_find_table( colst, nocs, ad, ca );
3918                 config_del_vals( ct, ca );
3919         }
3920         if ( cfn->c_om_head ) {
3921                 struct berval bv = BER_BVC("olcObjectIdentifier");
3922                 ad = NULL;
3923                 slap_bv2ad( &bv, &ad, &text );
3924                 ct = config_find_table( colst, nocs, ad, ca );
3925                 config_del_vals( ct, ca );
3926         }
3927         cfo = p->ce_private;
3928         cfo->c_kids = cfn->c_sibs;
3929         ch_free( cfn );
3930 }
3931
3932 static int
3933 config_add_oc( ConfigOCs **cop, CfEntryInfo *last, Entry *e, ConfigArgs *ca )
3934 {
3935         int             rc = LDAP_CONSTRAINT_VIOLATION;
3936         ObjectClass     **ocp;
3937
3938         if ( (*cop)->co_ldadd ) {
3939                 rc = (*cop)->co_ldadd( last, e, ca );
3940                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3941                         return rc;
3942                 }
3943         }
3944
3945         for ( ocp = (*cop)->co_oc->soc_sups; ocp && *ocp; ocp++ ) {
3946                 ConfigOCs       co = { 0 };
3947
3948                 co.co_name = &(*ocp)->soc_cname;
3949                 *cop = avl_find( CfOcTree, &co, CfOc_cmp );
3950                 if ( *cop == NULL ) {
3951                         return rc;
3952                 }
3953
3954                 rc = config_add_oc( cop, last, e, ca );
3955                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3956                         return rc;
3957                 }
3958         }
3959
3960         return rc;
3961 }
3962
3963 /* Parse an LDAP entry into config directives */
3964 static int
3965 config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca, SlapReply *rs,
3966         int *renum, Operation *op )
3967 {
3968         CfEntryInfo     *ce, *last = NULL;
3969         ConfigOCs       co, *coptr, **colst;
3970         Attribute       *a, *oc_at, *soc_at;
3971         int             i, ibase = -1, nocs, rc = 0;
3972         struct berval   pdn;
3973         ConfigTable     *ct;
3974         char            *ptr, *log_prefix = op ? op->o_log_prefix : "";
3975
3976         memset( ca, 0, sizeof(ConfigArgs));
3977
3978         /* Make sure parent exists and entry does not. But allow
3979          * Databases and Overlays to be inserted. Don't do any
3980          * auto-renumbering if manageDSAit control is present.
3981          */
3982         ce = config_find_base( cfb->cb_root, &e->e_nname, &last );
3983         if ( ce ) {
3984                 if ( ( op && op->o_managedsait ) ||
3985                         ( ce->ce_type != Cft_Database && ce->ce_type != Cft_Overlay &&
3986                           ce->ce_type != Cft_Module ) )
3987                 {
3988                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3989                                 "DN=\"%s\" already exists\n",
3990                                 log_prefix, e->e_name.bv_val, 0 );
3991                         return LDAP_ALREADY_EXISTS;
3992                 }
3993         }
3994
3995         dnParent( &e->e_nname, &pdn );
3996
3997         /* If last is NULL, the new entry is the root/suffix entry, 
3998          * otherwise last should be the parent.
3999          */
4000         if ( last && !dn_match( &last->ce_entry->e_nname, &pdn ) ) {
4001                 if ( rs ) {
4002                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4003                 }
4004                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4005                         "DN=\"%s\" not child of DN=\"%s\"\n",
4006                         log_prefix, e->e_name.bv_val,
4007                         last->ce_entry->e_name.bv_val );
4008                 return LDAP_NO_SUCH_OBJECT;
4009         }
4010
4011         if ( op ) {
4012                 /* No parent, must be root. This will never happen... */
4013                 if ( !last && !be_isroot( op ) && !be_shadow_update( op ) ) {
4014                         return LDAP_NO_SUCH_OBJECT;
4015                 }
4016
4017                 if ( last && !access_allowed( op, last->ce_entry,
4018                         slap_schema.si_ad_children, NULL, ACL_WADD, NULL ) )
4019                 {
4020                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4021                                 "DN=\"%s\" no write access to \"children\" of parent\n",
4022                                 log_prefix, e->e_name.bv_val, 0 );
4023                         return LDAP_INSUFFICIENT_ACCESS;
4024                 }
4025         }
4026
4027         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
4028         if ( !oc_at ) {
4029                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4030                         "DN=\"%s\" no objectClass\n",
4031                         log_prefix, e->e_name.bv_val, 0 );
4032                 return LDAP_OBJECT_CLASS_VIOLATION;
4033         }
4034
4035         soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4036         if ( !soc_at ) {
4037                 ObjectClass     *soc = NULL;
4038                 char            textbuf[ SLAP_TEXT_BUFLEN ];
4039                 const char      *text = textbuf;
4040
4041                 /* FIXME: check result */
4042                 rc = structural_class( oc_at->a_nvals, &soc, NULL,
4043                         &text, textbuf, sizeof(textbuf), NULL );
4044                 if ( rc != LDAP_SUCCESS ) {
4045                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4046                                 "DN=\"%s\" no structural objectClass (%s)\n",
4047                                 log_prefix, e->e_name.bv_val, text );
4048                         return rc;
4049                 }
4050                 attr_merge_one( e, slap_schema.si_ad_structuralObjectClass, &soc->soc_cname, NULL );
4051                 soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4052                 if ( soc_at == NULL ) {
4053                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4054                                 "DN=\"%s\" no structural objectClass; "
4055                                 "unable to merge computed class %s\n",
4056                                 log_prefix, e->e_name.bv_val,
4057                                 soc->soc_cname.bv_val );
4058                         return LDAP_OBJECT_CLASS_VIOLATION;
4059                 }
4060
4061                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4062                         "DN=\"%s\" no structural objectClass; "
4063                         "computed objectClass %s merged\n",
4064                         log_prefix, e->e_name.bv_val,
4065                         soc->soc_cname.bv_val );
4066         }
4067
4068         /* Fake the coordinates based on whether we're part of an
4069          * LDAP Add or if reading the config dir
4070          */
4071         if ( rs ) {
4072                 ca->fname = "slapd";
4073                 ca->lineno = 0;
4074         } else {
4075                 ca->fname = cfdir.bv_val;
4076                 ca->lineno = 1;
4077         }
4078         ca->ca_op = op;
4079
4080         co.co_name = &soc_at->a_nvals[0];
4081         coptr = avl_find( CfOcTree, &co, CfOc_cmp );
4082         if ( coptr == NULL ) {
4083                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4084                         "DN=\"%s\" no structural objectClass in configuration table\n",
4085                         log_prefix, e->e_name.bv_val, 0 );
4086                 return LDAP_OBJECT_CLASS_VIOLATION;
4087         }
4088
4089         /* Only the root can be Cft_Global, everything else must
4090          * have a parent. Only limited nesting arrangements are allowed.
4091          */
4092         rc = LDAP_CONSTRAINT_VIOLATION;
4093         if ( coptr->co_type == Cft_Global && !last ) {
4094                 cfn = cfb->cb_config;
4095                 ca->private = cfn;
4096                 ca->be = frontendDB;    /* just to get past check_vals */
4097                 rc = LDAP_SUCCESS;
4098         }
4099
4100         /* Check whether the Add is allowed by its parent, and do
4101          * any necessary arg setup
4102          */
4103         if ( last ) {
4104                 rc = config_add_oc( &coptr, last, e, ca );
4105                 if ( rc == LDAP_CONSTRAINT_VIOLATION ) {
4106                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4107                                 "DN=\"%s\" no structural objectClass add function\n",
4108                                 log_prefix, e->e_name.bv_val, 0 );
4109                         return LDAP_OBJECT_CLASS_VIOLATION;
4110                 }
4111         }
4112
4113         colst = count_ocs( oc_at, &nocs );
4114
4115         /* Add the entry but don't parse it, we already have its contents */
4116         if ( rc == LDAP_COMPARE_TRUE ) {
4117                 rc = LDAP_SUCCESS;
4118                 goto ok;
4119         }
4120
4121         if ( rc != LDAP_SUCCESS )
4122                 goto done_noop;
4123
4124         /* Parse all the values and check for simple syntax errors before
4125          * performing any set actions.
4126          *
4127          * If doing an LDAPadd, check for indexed names and any necessary
4128          * renaming/renumbering. Entries that don't need indexed names are
4129          * ignored. Entries that need an indexed name and arrive without one
4130          * are assigned to the end. Entries that arrive with an index may
4131          * cause the following entries to be renumbered/bumped down.
4132          *
4133          * Note that "pseudo-indexed" entries (cn=Include{xx}, cn=Module{xx})
4134          * don't allow Adding an entry with an index that's already in use.
4135          * This is flagged as an error (LDAP_ALREADY_EXISTS) up above.
4136          *
4137          * These entries can have auto-assigned indexes (appended to the end)
4138          * but only the other types support auto-renumbering of siblings.
4139          */
4140         {
4141                 rc = check_name_index( last, coptr->co_type, e, rs, renum,
4142                         &ibase );
4143                 if ( rc ) {
4144                         goto done_noop;
4145                 }
4146                 if ( renum && *renum && coptr->co_type != Cft_Database &&
4147                         coptr->co_type != Cft_Overlay )
4148                 {
4149                         snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
4150                                 "operation requires sibling renumbering" );
4151                         rc = LDAP_UNWILLING_TO_PERFORM;
4152                         goto done_noop;
4153                 }
4154         }
4155
4156         init_config_argv( ca );
4157
4158         /* Make sure we process attrs in the required order */
4159         sort_attrs( e, colst, nocs );
4160
4161         for ( a = e->e_attrs; a; a = a->a_next ) {
4162                 if ( a == oc_at ) continue;
4163                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4164                 if ( !ct ) continue;    /* user data? */
4165                 rc = check_vals( ct, ca, a, 1 );
4166                 if ( rc ) goto done_noop;
4167         }
4168
4169         /* Basic syntax checks are OK. Do the actual settings. */
4170         for ( a=e->e_attrs; a; a=a->a_next ) {
4171                 if ( a == oc_at ) continue;
4172                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4173                 if ( !ct ) continue;    /* user data? */
4174                 for (i=0; a->a_vals[i].bv_val; i++) {
4175                         char *iptr = NULL;
4176                         ca->line = a->a_vals[i].bv_val;
4177                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED ) {
4178                                 ptr = strchr( ca->line, '}' );
4179                                 if ( ptr ) {
4180                                         iptr = strchr( ca->line, '{' );
4181                                         ca->line = ptr+1;
4182                                 }
4183                         }
4184                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED_SIB ) {
4185                                 if ( iptr ) {
4186                                         ca->valx = strtol( iptr+1, NULL, 0 );
4187                                 } else {
4188                                         ca->valx = -1;
4189                                 }
4190                         } else {
4191                                 ca->valx = i;
4192                         }
4193                         rc = config_parse_add( ct, ca, i );
4194                         if ( rc ) {
4195                                 rc = LDAP_OTHER;
4196                                 goto done;
4197                         }
4198                 }
4199         }
4200 ok:
4201         /* Newly added databases and overlays need to be started up */
4202         if ( CONFIG_ONLINE_ADD( ca )) {
4203                 if ( colst[0]->co_type == Cft_Database ) {
4204                         rc = backend_startup_one( ca->be, &ca->reply );
4205
4206                 } else if ( colst[0]->co_type == Cft_Overlay ) {
4207                         if ( ca->bi->bi_db_open ) {
4208                                 BackendInfo *bi_orig = ca->be->bd_info;
4209                                 ca->be->bd_info = ca->bi;
4210                                 rc = ca->bi->bi_db_open( ca->be, &ca->reply );
4211                                 ca->be->bd_info = bi_orig;
4212                         }
4213                 }
4214                 if ( rc ) {
4215                         if (ca->cr_msg[0] == '\0')
4216                                 snprintf( ca->cr_msg, sizeof( ca->cr_msg ), "<%s> failed startup", ca->argv[0] );
4217
4218                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
4219                                 ca->log, ca->cr_msg, ca->argv[1] );
4220                         rc = LDAP_OTHER;
4221                         goto done;
4222                 }
4223         }
4224
4225         ca->valx = ibase;
4226         ce = ch_calloc( 1, sizeof(CfEntryInfo) );
4227         ce->ce_parent = last;
4228         ce->ce_entry = entry_dup( e );
4229         ce->ce_entry->e_private = ce;
4230         ce->ce_type = colst[0]->co_type;
4231         ce->ce_be = ca->be;
4232         ce->ce_bi = ca->bi;
4233         ce->ce_private = ca->private;
4234         ca->ca_entry = ce->ce_entry;
4235         if ( !last ) {
4236                 cfb->cb_root = ce;
4237         } else if ( last->ce_kids ) {
4238                 CfEntryInfo *c2, **cprev;
4239
4240                 /* Advance to first of this type */
4241                 cprev = &last->ce_kids;
4242                 for ( c2 = *cprev; c2 && c2->ce_type < ce->ce_type; ) {
4243                         cprev = &c2->ce_sibs;
4244                         c2 = c2->ce_sibs;
4245                 }
4246                 /* Account for the (-1) frontendDB entry */
4247                 if ( ce->ce_type == Cft_Database ) {
4248                         if ( ca->be == frontendDB )
4249                                 ibase = 0;
4250                         else if ( ibase != -1 )
4251                                 ibase++;
4252                 }
4253                 /* Append */
4254                 if ( ibase < 0 ) {
4255                         for (c2 = *cprev; c2 && c2->ce_type == ce->ce_type;) {
4256                                 cprev = &c2->ce_sibs;
4257                                 c2 = c2->ce_sibs;
4258                         }
4259                 } else {
4260                 /* Insert */
4261                         int i;
4262                         for ( i=0; i<ibase; i++ ) {
4263                                 c2 = *cprev;
4264                                 cprev = &c2->ce_sibs;
4265                         }
4266                 }
4267                 ce->ce_sibs = *cprev;
4268                 *cprev = ce;
4269         } else {
4270                 last->ce_kids = ce;
4271         }
4272
4273 done:
4274         if ( rc ) {
4275                 if ( (colst[0]->co_type == Cft_Database) && ca->be ) {
4276                         if ( ca->be != frontendDB )
4277                                 backend_destroy_one( ca->be, 1 );
4278                 } else if ( (colst[0]->co_type == Cft_Overlay) && ca->bi ) {
4279                         overlay_destroy_one( ca->be, (slap_overinst *)ca->bi );
4280                 } else if ( colst[0]->co_type == Cft_Schema ) {
4281                         schema_destroy_one( ca, colst, nocs, last );
4282                 }
4283         }
4284 done_noop:
4285
4286         ch_free( ca->argv );
4287         if ( colst ) ch_free( colst );
4288         return rc;
4289 }
4290
4291 #define BIGTMP  10000
4292 static int
4293 config_rename_add( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4294         int base, int rebase, int max, int use_ldif )
4295 {
4296         CfEntryInfo *ce2, *ce3, *cetmp = NULL, *cerem = NULL;
4297         ConfigType etype = ce->ce_type;
4298         int count = 0, rc = 0;
4299
4300         /* Reverse ce list */
4301         for (ce2 = ce->ce_sibs;ce2;ce2 = ce3) {
4302                 if (ce2->ce_type != etype) {
4303                         cerem = ce2;
4304                         break;
4305                 }
4306                 ce3 = ce2->ce_sibs;
4307                 ce2->ce_sibs = cetmp;
4308                 cetmp = ce2;
4309                 count++;
4310                 if ( max && count >= max ) {
4311                         cerem = ce3;
4312                         break;
4313                 }
4314         }
4315
4316         /* Move original to a temp name until increments are done */
4317         if ( rebase ) {
4318                 ce->ce_entry->e_private = NULL;
4319                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4320                         base+BIGTMP, 0, use_ldif );
4321                 ce->ce_entry->e_private = ce;
4322         }
4323         /* start incrementing */
4324         for (ce2=cetmp; ce2; ce2=ce3) {
4325                 ce3 = ce2->ce_sibs;
4326                 ce2->ce_sibs = cerem;
4327                 cerem = ce2;
4328                 if ( rc == 0 ) 
4329                         rc = config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4330                                 count+base, 0, use_ldif );
4331                 count--;
4332         }
4333         if ( rebase )
4334                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4335                         base, 0, use_ldif );
4336         return rc;
4337 }
4338
4339 static int
4340 config_rename_del( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4341         CfEntryInfo *ce2, int old, int use_ldif )
4342 {
4343         int count = 0;
4344
4345         /* Renumber original to a temp value */
4346         ce->ce_entry->e_private = NULL;
4347         config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4348                 old+BIGTMP, 0, use_ldif );
4349         ce->ce_entry->e_private = ce;
4350
4351         /* start decrementing */
4352         for (; ce2 != ce; ce2=ce2->ce_sibs) {
4353                 config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4354                         count+old, 0, use_ldif );
4355                 count++;
4356         }
4357         return config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4358                 count+old, 0, use_ldif );
4359 }
4360
4361 /* Parse an LDAP entry into config directives, then store in underlying
4362  * database.
4363  */
4364 static int
4365 config_back_add( Operation *op, SlapReply *rs )
4366 {
4367         CfBackInfo *cfb;
4368         int renumber;
4369         ConfigArgs ca;
4370
4371         if ( !access_allowed( op, op->ora_e, slap_schema.si_ad_entry,
4372                 NULL, ACL_WADD, NULL )) {
4373                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4374                 goto out;
4375         }
4376
4377         cfb = (CfBackInfo *)op->o_bd->be_private;
4378
4379         /* add opattrs for syncprov */
4380         {
4381                 char textbuf[SLAP_TEXT_BUFLEN];
4382                 size_t textlen = sizeof textbuf;
4383                 rs->sr_err = entry_schema_check(op, op->ora_e, NULL, 0, 1,
4384                         &rs->sr_text, textbuf, sizeof( textbuf ) );
4385                 if ( rs->sr_err != LDAP_SUCCESS )
4386                         goto out;
4387                 rs->sr_err = slap_add_opattrs( op, &rs->sr_text, textbuf, textlen, 1 );
4388                 if ( rs->sr_err != LDAP_SUCCESS ) {
4389                         Debug( LDAP_DEBUG_TRACE,
4390                                 LDAP_XSTRING(config_back_add) ": entry failed op attrs add: "
4391                                 "%s (%d)\n", rs->sr_text, rs->sr_err, 0 );
4392                         goto out;
4393                 }
4394         }
4395
4396         ldap_pvt_thread_pool_pause( &connection_pool );
4397
4398         /* Strategy:
4399          * 1) check for existence of entry
4400          * 2) check for sibling renumbering
4401          * 3) perform internal add
4402          * 4) perform any necessary renumbering
4403          * 5) store entry in underlying database
4404          */
4405         rs->sr_err = config_add_internal( cfb, op->ora_e, &ca, rs, &renumber, op );
4406         if ( rs->sr_err != LDAP_SUCCESS ) {
4407                 rs->sr_text = ca.cr_msg;
4408                 goto out2;
4409         }
4410
4411         if ( renumber ) {
4412                 CfEntryInfo *ce = ca.ca_entry->e_private;
4413                 req_add_s addr = op->oq_add;
4414                 op->o_tag = LDAP_REQ_MODRDN;
4415                 rs->sr_err = config_rename_add( op, rs, ce, ca.valx, 0, 0, cfb->cb_use_ldif );
4416                 op->o_tag = LDAP_REQ_ADD;
4417                 op->oq_add = addr;
4418                 if ( rs->sr_err != LDAP_SUCCESS ) {
4419                         goto out2;
4420                 }
4421         }
4422
4423         if ( cfb->cb_use_ldif ) {
4424                 BackendDB *be = op->o_bd;
4425                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4426                 struct berval dn, ndn;
4427
4428                 op->o_bd = &cfb->cb_db;
4429
4430                 /* Save current rootdn; use the underlying DB's rootdn */
4431                 dn = op->o_dn;
4432                 ndn = op->o_ndn;
4433                 op->o_dn = op->o_bd->be_rootdn;
4434                 op->o_ndn = op->o_bd->be_rootndn;
4435
4436                 scp = op->o_callback;
4437                 op->o_callback = &sc;
4438                 op->o_bd->be_add( op, rs );
4439                 op->o_bd = be;
4440                 op->o_callback = scp;
4441                 op->o_dn = dn;
4442                 op->o_ndn = ndn;
4443         }
4444
4445 out2:;
4446         ldap_pvt_thread_pool_resume( &connection_pool );
4447
4448 out:;
4449         send_ldap_result( op, rs );
4450         slap_graduate_commit_csn( op );
4451         return rs->sr_err;
4452 }
4453
4454 typedef struct delrec {
4455         struct delrec *next;
4456         int nidx;
4457         int idx[1];
4458 } delrec;
4459
4460 static int
4461 config_modify_add( ConfigTable *ct, ConfigArgs *ca, AttributeDescription *ad,
4462         int i )
4463 {
4464         int rc;
4465
4466         if (ad->ad_type->sat_flags & SLAP_AT_ORDERED &&
4467                 ca->line[0] == '{' )
4468         {
4469                 char *ptr = strchr( ca->line + 1, '}' );
4470                 if ( ptr ) {
4471                         char    *next;
4472
4473                         ca->valx = strtol( ca->line + 1, &next, 0 );
4474                         if ( next == ca->line + 1 || next[ 0 ] != '}' ) {
4475                                 return LDAP_OTHER;
4476                         }
4477                         ca->line = ptr+1;
4478                 }
4479         }
4480         rc = config_parse_add( ct, ca, i );
4481         if ( rc ) {
4482                 rc = LDAP_OTHER;
4483         }
4484         return rc;
4485 }
4486
4487 static int
4488 config_modify_internal( CfEntryInfo *ce, Operation *op, SlapReply *rs,
4489         ConfigArgs *ca )
4490 {
4491         int rc = LDAP_UNWILLING_TO_PERFORM;
4492         Modifications *ml;
4493         Entry *e = ce->ce_entry;
4494         Attribute *save_attrs = e->e_attrs, *oc_at, *s, *a;
4495         ConfigTable *ct;
4496         ConfigOCs **colst;
4497         int i, nocs;
4498         char *ptr;
4499         delrec *dels = NULL, *deltail = NULL;
4500
4501         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
4502         if ( !oc_at ) return LDAP_OBJECT_CLASS_VIOLATION;
4503
4504         colst = count_ocs( oc_at, &nocs );
4505
4506         /* make sure add/del flags are clear; should always be true */
4507         for ( s = save_attrs; s; s = s->a_next ) {
4508                 s->a_flags &= ~(SLAP_ATTR_IXADD|SLAP_ATTR_IXDEL);
4509         }
4510
4511         e->e_attrs = attrs_dup( e->e_attrs );
4512
4513         init_config_argv( ca );
4514         ca->be = ce->ce_be;
4515         ca->bi = ce->ce_bi;
4516         ca->private = ce->ce_private;
4517         ca->ca_entry = e;
4518         ca->fname = "slapd";
4519         ca->ca_op = op;
4520         strcpy( ca->log, "back-config" );
4521
4522         for (ml = op->orm_modlist; ml; ml=ml->sml_next) {
4523                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4524                 switch (ml->sml_op) {
4525                 case LDAP_MOD_DELETE:
4526                 case LDAP_MOD_REPLACE: {
4527                         BerVarray vals = NULL, nvals = NULL;
4528                         int *idx = NULL;
4529                         if ( ct && ( ct->arg_type & ARG_NO_DELETE )) {
4530                                 rc = LDAP_OTHER;
4531                                 snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot delete %s",
4532                                         ml->sml_desc->ad_cname.bv_val );
4533                                 goto out_noop;
4534                         }
4535                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4536                                 vals = ml->sml_values;
4537                                 nvals = ml->sml_nvalues;
4538                                 ml->sml_values = NULL;
4539                                 ml->sml_nvalues = NULL;
4540                         }
4541                         /* If we're deleting by values, remember the indexes of the
4542                          * values we deleted.
4543                          */
4544                         if ( ct && ml->sml_values ) {
4545                                 delrec *d;
4546                                 for (i=0; ml->sml_values[i].bv_val; i++);
4547                                 d = ch_malloc( sizeof(delrec) + (i - 1)* sizeof(int));
4548                                 d->nidx = i;
4549                                 d->next = NULL;
4550                                 if ( dels ) {
4551                                         deltail->next = d;
4552                                 } else {
4553                                         dels = d;
4554                                 }
4555                                 deltail = d;
4556                                 idx = d->idx;
4557                         }
4558                         rc = modify_delete_vindex(e, &ml->sml_mod,
4559                                 get_permissiveModify(op),
4560                                 &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg), idx );
4561                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4562                                 ml->sml_values = vals;
4563                                 ml->sml_nvalues = nvals;
4564                         }
4565                         if ( !vals )
4566                                 break;
4567                         }
4568                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4569
4570                 case LDAP_MOD_ADD:
4571                 case SLAP_MOD_SOFTADD: {
4572                         int mop = ml->sml_op;
4573                         int navals = -1;
4574                         ml->sml_op = LDAP_MOD_ADD;
4575                         if ( ct ) {
4576                                 if ( ct->arg_type & ARG_NO_INSERT ) {
4577                                         Attribute *a = attr_find( e->e_attrs, ml->sml_desc );
4578                                         if ( a ) {
4579                                                 for (i = 0; a->a_vals[i].bv_val; i++ );
4580                                                 navals = i;
4581                                         }
4582                                 }
4583                                 for ( i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++ ) {
4584                                         if ( ml->sml_values[i].bv_val[0] == '{' &&
4585                                                 navals >= 0 )
4586                                         {
4587                                                 char    *next, *val = ml->sml_values[i].bv_val + 1;
4588                                                 int     j;
4589
4590                                                 j = strtol( val, &next, 0 );
4591                                                 if ( next == val || next[ 0 ] != '}' || j < navals ) {
4592                                                         rc = LDAP_OTHER;
4593                                                         snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot insert %s",
4594                                                                 ml->sml_desc->ad_cname.bv_val );
4595                                                         goto out_noop;
4596                                                 }
4597                                         }
4598                                         rc = check_vals( ct, ca, ml, 0 );
4599                                         if ( rc ) goto out_noop;
4600                                 }
4601                         }
4602                         rc = modify_add_values(e, &ml->sml_mod,
4603                                    get_permissiveModify(op),
4604                                    &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4605
4606                         /* If value already exists, show success here
4607                          * and ignore this operation down below.
4608                          */
4609                         if ( mop == SLAP_MOD_SOFTADD ) {
4610                                 if ( rc == LDAP_TYPE_OR_VALUE_EXISTS )
4611                                         rc = LDAP_SUCCESS;
4612                                 else
4613                                         mop = LDAP_MOD_ADD;
4614                         }
4615                         ml->sml_op = mop;
4616                         break;
4617                         }
4618
4619                         break;
4620                 case LDAP_MOD_INCREMENT:        /* FIXME */
4621                         break;
4622                 default:
4623                         break;
4624                 }
4625                 if(rc != LDAP_SUCCESS) break;
4626         }
4627         
4628         if ( rc == LDAP_SUCCESS) {
4629                 /* check that the entry still obeys the schema */
4630                 rc = entry_schema_check(op, e, NULL, 0, 0,
4631                         &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4632                 if ( rc ) goto out_noop;
4633         }
4634         /* Basic syntax checks are OK. Do the actual settings. */
4635         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4636                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4637                 if ( !ct ) continue;
4638
4639                 s = attr_find( save_attrs, ml->sml_desc );
4640                 a = attr_find( e->e_attrs, ml->sml_desc );
4641
4642                 switch (ml->sml_op) {
4643                 case LDAP_MOD_DELETE:
4644                 case LDAP_MOD_REPLACE: {
4645                         BerVarray vals = NULL, nvals = NULL;
4646                         delrec *d = NULL;
4647
4648                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4649                                 vals = ml->sml_values;
4650                                 nvals = ml->sml_nvalues;
4651                                 ml->sml_values = NULL;
4652                                 ml->sml_nvalues = NULL;
4653                         }
4654
4655                         if ( ml->sml_values )
4656                                 d = dels;
4657
4658                         /* If we didn't delete the whole attribute */
4659                         if ( ml->sml_values && a ) {
4660                                 struct berval *mvals;
4661                                 int j;
4662
4663                                 if ( ml->sml_nvalues )
4664                                         mvals = ml->sml_nvalues;
4665                                 else
4666                                         mvals = ml->sml_values;
4667
4668                                 /* use the indexes we saved up above */
4669                                 for (i=0; i < d->nidx; i++) {
4670                                         struct berval bv = *mvals++;
4671                                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED &&
4672                                                 bv.bv_val[0] == '{' ) {
4673                                                 ptr = strchr( bv.bv_val, '}' ) + 1;
4674                                                 bv.bv_len -= ptr - bv.bv_val;
4675                                                 bv.bv_val = ptr;
4676                                         }
4677                                         ca->line = bv.bv_val;
4678                                         ca->valx = d->idx[i];
4679                                         rc = config_del_vals( ct, ca );
4680                                         if ( rc != LDAP_SUCCESS ) break;
4681                                         if ( s )
4682                                                 s->a_flags |= SLAP_ATTR_IXDEL;
4683                                         for (j=i+1; j < d->nidx; j++)
4684                                                 if ( d->idx[j] >d->idx[i] )
4685                                                         d->idx[j]--;
4686                                 }
4687                         } else {
4688                                 ca->valx = -1;
4689                                 ca->line = NULL;
4690                                 rc = config_del_vals( ct, ca );
4691                                 if ( rc ) rc = LDAP_OTHER;
4692                                 if ( s )
4693                                         s->a_flags |= SLAP_ATTR_IXDEL;
4694                         }
4695                         if ( ml->sml_values ) {
4696                                 d = d->next;
4697                                 ch_free( dels );
4698                                 dels = d;
4699                         }
4700                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4701                                 ml->sml_values = vals;
4702                                 ml->sml_nvalues = nvals;
4703                         }
4704                         if ( !vals || rc != LDAP_SUCCESS )
4705                                 break;
4706                         }
4707                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4708
4709                 case LDAP_MOD_ADD:
4710                         for (i=0; ml->sml_values[i].bv_val; i++) {
4711                                 ca->line = ml->sml_values[i].bv_val;
4712                                 ca->valx = -1;
4713                                 rc = config_modify_add( ct, ca, ml->sml_desc, i );
4714                                 if ( rc )
4715                                         goto out;
4716                                 a->a_flags |= SLAP_ATTR_IXADD;
4717                         }
4718                         break;
4719                 }
4720         }
4721
4722 out:
4723         /* Undo for a failed operation */
4724         if ( rc != LDAP_SUCCESS ) {
4725                 for ( s = save_attrs; s; s = s->a_next ) {
4726                         if ( s->a_flags & SLAP_ATTR_IXDEL ) {
4727                                 s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4728                                 ct = config_find_table( colst, nocs, s->a_desc, ca );
4729                                 a = attr_find( e->e_attrs, s->a_desc );
4730                                 if ( a ) {
4731                                         /* clear the flag so the add check below will skip it */
4732                                         a->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4733                                         ca->valx = -1;
4734                                         ca->line = NULL;
4735                                         config_del_vals( ct, ca );
4736                                 }
4737                                 for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4738                                         ca->line = s->a_vals[i].bv_val;
4739                                         ca->valx = -1;
4740                                         config_modify_add( ct, ca, s->a_desc, i );
4741                                 }
4742                         }
4743                 }
4744                 for ( a = e->e_attrs; a; a = a->a_next ) {
4745                         if ( a->a_flags & SLAP_ATTR_IXADD ) {
4746                                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4747                                 ca->valx = -1;
4748                                 ca->line = NULL;
4749                                 config_del_vals( ct, ca );
4750                                 s = attr_find( save_attrs, a->a_desc );
4751                                 if ( s ) {
4752                                         s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4753                                         for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4754                                                 ca->line = s->a_vals[i].bv_val;
4755                                                 ca->valx = -1;
4756                                                 config_modify_add( ct, ca, s->a_desc, i );
4757                                         }
4758                                 }
4759                         }
4760                 }
4761         }
4762
4763         if ( ca->cleanup )
4764                 ca->cleanup( ca );
4765 out_noop:
4766         if ( rc == LDAP_SUCCESS ) {
4767                 attrs_free( save_attrs );
4768         } else {
4769                 attrs_free( e->e_attrs );
4770                 e->e_attrs = save_attrs;
4771         }
4772         ch_free( ca->argv );
4773         if ( colst ) ch_free( colst );
4774         while( dels ) {
4775                 deltail = dels->next;
4776                 ch_free( dels );
4777                 dels = deltail;
4778         }
4779
4780         return rc;
4781 }
4782
4783 static int
4784 config_back_modify( Operation *op, SlapReply *rs )
4785 {
4786         CfBackInfo *cfb;
4787         CfEntryInfo *ce, *last;
4788         Modifications *ml;
4789         ConfigArgs ca = {0};
4790         struct berval rdn;
4791         char *ptr;
4792         AttributeDescription *rad = NULL;
4793
4794         cfb = (CfBackInfo *)op->o_bd->be_private;
4795
4796         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4797         if ( !ce ) {
4798                 if ( last )
4799                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4800                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4801                 goto out;
4802         }
4803
4804         if ( !acl_check_modlist( op, ce->ce_entry, op->orm_modlist )) {
4805                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4806                 goto out;
4807         }
4808
4809         /* Get type of RDN */
4810         rdn = ce->ce_entry->e_nname;
4811         ptr = strchr( rdn.bv_val, '=' );
4812         rdn.bv_len = ptr - rdn.bv_val;
4813         slap_bv2ad( &rdn, &rad, &rs->sr_text );
4814
4815         /* Some basic validation... */
4816         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4817                 /* Don't allow Modify of RDN; must use ModRdn for that. */
4818                 if ( ml->sml_desc == rad ) {
4819                         rs->sr_err = LDAP_NOT_ALLOWED_ON_RDN;
4820                         rs->sr_text = "Use modrdn to change the entry name";
4821                         goto out;
4822                 }
4823         }
4824
4825         slap_mods_opattrs( op, &op->orm_modlist, 1 );
4826
4827         if ( !slapd_shutdown )
4828                 ldap_pvt_thread_pool_pause( &connection_pool );
4829
4830         /* Strategy:
4831          * 1) perform the Modify on the cached Entry.
4832          * 2) verify that the Entry still satisfies the schema.
4833          * 3) perform the individual config operations.
4834          * 4) store Modified entry in underlying LDIF backend.
4835          */
4836         rs->sr_err = config_modify_internal( ce, op, rs, &ca );
4837         if ( rs->sr_err ) {
4838                 rs->sr_text = ca.cr_msg;
4839         } else if ( cfb->cb_use_ldif ) {
4840                 BackendDB *be = op->o_bd;
4841                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4842                 struct berval dn, ndn;
4843
4844                 op->o_bd = &cfb->cb_db;
4845
4846                 dn = op->o_dn;
4847                 ndn = op->o_ndn;
4848                 op->o_dn = op->o_bd->be_rootdn;
4849                 op->o_ndn = op->o_bd->be_rootndn;
4850
4851                 scp = op->o_callback;
4852                 op->o_callback = &sc;
4853                 op->o_bd->be_modify( op, rs );
4854                 op->o_bd = be;
4855                 op->o_callback = scp;
4856                 op->o_dn = dn;
4857                 op->o_ndn = ndn;
4858         }
4859
4860         if ( !slapd_shutdown )
4861                 ldap_pvt_thread_pool_resume( &connection_pool );
4862 out:
4863         send_ldap_result( op, rs );
4864         slap_graduate_commit_csn( op );
4865         return rs->sr_err;
4866 }
4867
4868 static int
4869 config_back_modrdn( Operation *op, SlapReply *rs )
4870 {
4871         CfBackInfo *cfb;
4872         CfEntryInfo *ce, *last;
4873         struct berval rdn;
4874         int ixold, ixnew;
4875
4876         cfb = (CfBackInfo *)op->o_bd->be_private;
4877
4878         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4879         if ( !ce ) {
4880                 if ( last )
4881                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4882                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4883                 goto out;
4884         }
4885         if ( !access_allowed( op, ce->ce_entry, slap_schema.si_ad_entry,
4886                 NULL, ACL_WRITE, NULL )) {
4887                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4888                 goto out;
4889         }
4890         { Entry *parent;
4891                 if ( ce->ce_parent )
4892                         parent = ce->ce_parent->ce_entry;
4893                 else
4894                         parent = (Entry *)&slap_entry_root;
4895                 if ( !access_allowed( op, parent, slap_schema.si_ad_children,
4896                         NULL, ACL_WRITE, NULL )) {
4897                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4898                         goto out;
4899                 }
4900         }
4901
4902         /* We don't allow moving objects to new parents.
4903          * Generally we only allow reordering a set of ordered entries.
4904          */
4905         if ( op->orr_newSup ) {
4906                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4907                 goto out;
4908         }
4909
4910         /* If newRDN == oldRDN, quietly succeed */
4911         dnRdn( &op->o_req_ndn, &rdn );
4912         if ( dn_match( &rdn, &op->orr_nnewrdn )) {
4913                 rs->sr_err = LDAP_SUCCESS;
4914                 goto out;
4915         }
4916
4917         /* Current behavior, subject to change as needed:
4918          *
4919          * For backends and overlays, we only allow renumbering.
4920          * For schema, we allow renaming with the same number.
4921          * Otherwise, the op is not allowed.
4922          */
4923
4924         if ( ce->ce_type == Cft_Schema ) {
4925                 char *ptr1, *ptr2;
4926                 int len;
4927
4928                 /* Can't alter the main cn=schema entry */
4929                 if ( ce->ce_parent->ce_type == Cft_Global ) {
4930                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4931                         rs->sr_text = "renaming not allowed for this entry";
4932                         goto out;
4933                 }
4934
4935                 /* We could support this later if desired */
4936                 ptr1 = ber_bvchr( &rdn, '}' );
4937                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4938                 len = ptr1 - rdn.bv_val;
4939                 if ( len != ptr2 - op->orr_newrdn.bv_val ||
4940                         strncmp( rdn.bv_val, op->orr_newrdn.bv_val, len )) {
4941                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4942                         rs->sr_text = "schema reordering not supported";
4943                         goto out;
4944                 }
4945         } else if ( ce->ce_type == Cft_Database ||
4946                 ce->ce_type == Cft_Overlay ) {
4947                 char *ptr1, *ptr2, *iptr1, *iptr2;
4948                 int len1, len2;
4949
4950                 iptr2 = ber_bvchr( &op->orr_newrdn, '=' ) + 1;
4951                 if ( *iptr2 != '{' ) {
4952                         rs->sr_err = LDAP_NAMING_VIOLATION;
4953                         rs->sr_text = "new ordering index is required";
4954                         goto out;
4955                 }
4956                 iptr2++;
4957                 iptr1 = ber_bvchr( &rdn, '{' ) + 1;
4958                 ptr1 = ber_bvchr( &rdn, '}' );
4959                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4960                 if ( !ptr2 ) {
4961                         rs->sr_err = LDAP_NAMING_VIOLATION;
4962                         rs->sr_text = "new ordering index is required";
4963                         goto out;
4964                 }
4965
4966                 len1 = ptr1 - rdn.bv_val;
4967                 len2 = ptr2 - op->orr_newrdn.bv_val;
4968
4969                 if ( rdn.bv_len - len1 != op->orr_newrdn.bv_len - len2 ||
4970                         strncmp( ptr1, ptr2, rdn.bv_len - len1 )) {
4971                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4972                         rs->sr_text = "changing database/overlay type not allowed";
4973                         goto out;
4974                 }
4975                 ixold = strtol( iptr1, NULL, 0 );
4976                 ixnew = strtol( iptr2, &ptr1, 0 );
4977                 if ( ptr1 != ptr2 || ixold < 0 || ixnew < 0 ) {
4978                         rs->sr_err = LDAP_NAMING_VIOLATION;
4979                         goto out;
4980                 }
4981                 /* config DB is always 0, cannot be changed */
4982                 if ( ce->ce_type == Cft_Database && ( ixold == 0 || ixnew == 0 )) {
4983                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
4984                         goto out;
4985                 }
4986         } else {
4987                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4988                 rs->sr_text = "renaming not supported for this entry";
4989                 goto out;
4990         }
4991
4992         ldap_pvt_thread_pool_pause( &connection_pool );
4993
4994         if ( ce->ce_type == Cft_Schema ) {
4995                 req_modrdn_s modr = op->oq_modrdn;
4996                 struct berval rdn;
4997                 Attribute *a;
4998                 rs->sr_err = config_rename_attr( rs, ce->ce_entry, &rdn, &a );
4999                 if ( rs->sr_err == LDAP_SUCCESS ) {
5000                         rs->sr_err = config_rename_one( op, rs, ce->ce_entry,
5001                                 ce->ce_parent, a, &op->orr_newrdn, &op->orr_nnewrdn,
5002                                 cfb->cb_use_ldif );
5003                 }
5004                 op->oq_modrdn = modr;
5005         } else {
5006                 CfEntryInfo *ce2, *cebase, **cprev, **cbprev, *ceold;
5007                 req_modrdn_s modr = op->oq_modrdn;
5008                 int i;
5009
5010                 /* Advance to first of this type */
5011                 cprev = &ce->ce_parent->ce_kids;
5012                 for ( ce2 = *cprev; ce2 && ce2->ce_type != ce->ce_type; ) {
5013                         cprev = &ce2->ce_sibs;
5014                         ce2 = ce2->ce_sibs;
5015                 }
5016                 /* Skip the -1 entry */
5017                 if ( ce->ce_type == Cft_Database ) {
5018                         cprev = &ce2->ce_sibs;
5019                         ce2 = ce2->ce_sibs;
5020                 }
5021                 cebase = ce2;
5022                 cbprev = cprev;
5023
5024                 /* Remove from old slot */
5025                 for ( ce2 = *cprev; ce2 && ce2 != ce; ce2 = ce2->ce_sibs )
5026                         cprev = &ce2->ce_sibs;
5027                 *cprev = ce->ce_sibs;
5028                 ceold = ce->ce_sibs;
5029
5030                 /* Insert into new slot */
5031                 cprev = cbprev;
5032                 for ( i=0; i<ixnew; i++ ) {
5033                         ce2 = *cprev;
5034                         if ( !ce2 )
5035                                 break;
5036                         cprev = &ce2->ce_sibs;
5037                 }
5038                 ce->ce_sibs = *cprev;
5039                 *cprev = ce;
5040
5041                 ixnew = i;
5042
5043                 /* NOTE: These should be encoded in the OC tables, not inline here */
5044                 if ( ce->ce_type == Cft_Database )
5045                         backend_db_move( ce->ce_be, ixnew );
5046                 else if ( ce->ce_type == Cft_Overlay )
5047                         overlay_move( ce->ce_be, (slap_overinst *)ce->ce_bi, ixnew );
5048                         
5049                 if ( ixold < ixnew ) {
5050                         rs->sr_err = config_rename_del( op, rs, ce, ceold, ixold,
5051                                 cfb->cb_use_ldif );
5052                 } else {
5053                         rs->sr_err = config_rename_add( op, rs, ce, ixnew, 1,
5054                                 ixold - ixnew, cfb->cb_use_ldif );
5055                 }
5056                 op->oq_modrdn = modr;
5057         }
5058
5059         ldap_pvt_thread_pool_resume( &connection_pool );
5060 out:
5061         send_ldap_result( op, rs );
5062         return rs->sr_err;
5063 }
5064
5065 static int
5066 config_back_delete( Operation *op, SlapReply *rs )
5067 {
5068         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, NULL );
5069         return rs->sr_err;
5070 }
5071
5072 static int
5073 config_back_search( Operation *op, SlapReply *rs )
5074 {
5075         CfBackInfo *cfb;
5076         CfEntryInfo *ce, *last;
5077         slap_mask_t mask;
5078
5079         cfb = (CfBackInfo *)op->o_bd->be_private;
5080
5081         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
5082         if ( !ce ) {
5083                 if ( last )
5084                         rs->sr_matched = last->ce_entry->e_name.bv_val;
5085                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
5086                 goto out;
5087         }
5088         if ( !access_allowed_mask( op, ce->ce_entry, slap_schema.si_ad_entry, NULL,
5089                 ACL_SEARCH, NULL, &mask ))
5090         {
5091                 if ( !ACL_GRANT( mask, ACL_DISCLOSE )) {
5092                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
5093                 } else {
5094                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
5095                 }
5096                 goto out;
5097         }
5098         switch ( op->ors_scope ) {
5099         case LDAP_SCOPE_BASE:
5100         case LDAP_SCOPE_SUBTREE:
5101                 config_send( op, rs, ce, 0 );
5102                 break;
5103                 
5104         case LDAP_SCOPE_ONELEVEL:
5105                 for (ce = ce->ce_kids; ce; ce=ce->ce_sibs) {
5106                         config_send( op, rs, ce, 1 );
5107                 }
5108                 break;
5109         }
5110                 
5111         rs->sr_err = LDAP_SUCCESS;
5112 out:
5113         send_ldap_result( op, rs );
5114         return 0;
5115 }
5116
5117 /* no-op, we never free entries */
5118 int config_entry_release(
5119         Operation *op,
5120         Entry *e,
5121         int rw )
5122 {
5123         if ( !e->e_private ) {
5124                 entry_free( e );
5125         }
5126         return LDAP_SUCCESS;
5127 }
5128
5129 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
5130  */
5131 int config_back_entry_get(
5132         Operation *op,
5133         struct berval *ndn,
5134         ObjectClass *oc,
5135         AttributeDescription *at,
5136         int rw,
5137         Entry **ent )
5138 {
5139         CfBackInfo *cfb;
5140         CfEntryInfo *ce, *last;
5141
5142         cfb = (CfBackInfo *)op->o_bd->be_private;
5143
5144         ce = config_find_base( cfb->cb_root, ndn, &last );
5145         if ( ce ) {
5146                 *ent = ce->ce_entry;
5147                 if ( *ent && oc && !is_entry_objectclass_or_sub( *ent, oc ) ) {
5148                         *ent = NULL;
5149                 }
5150         }
5151
5152         return ( *ent == NULL ? 1 : 0 );
5153 }
5154
5155 static void
5156 config_build_attrs( Entry *e, AttributeType **at, AttributeDescription *ad,
5157         ConfigTable *ct, ConfigArgs *c )
5158 {
5159         int i, rc;
5160
5161         for (; at && *at; at++) {
5162                 /* Skip the naming attr */
5163                 if ((*at)->sat_ad == ad || (*at)->sat_ad == slap_schema.si_ad_cn )
5164                         continue;
5165                 for (i=0;ct[i].name;i++) {
5166                         if (ct[i].ad == (*at)->sat_ad) {
5167                                 rc = config_get_vals(&ct[i], c);
5168                                 /* NOTE: tolerate that config_get_vals()
5169                                  * returns success with no values */
5170                                 if (rc == LDAP_SUCCESS && c->rvalue_vals != NULL ) {
5171                                         if ( c->rvalue_nvals )
5172                                                 attr_merge(e, ct[i].ad, c->rvalue_vals,
5173                                                         c->rvalue_nvals);
5174                                         else
5175                                                 attr_merge_normalize(e, ct[i].ad,
5176                                                         c->rvalue_vals, NULL);
5177                                         ber_bvarray_free( c->rvalue_nvals );
5178                                         ber_bvarray_free( c->rvalue_vals );
5179                                 }
5180                                 break;
5181                         }
5182                 }
5183         }
5184 }
5185
5186 Entry *
5187 config_build_entry( Operation *op, SlapReply *rs, CfEntryInfo *parent,
5188         ConfigArgs *c, struct berval *rdn, ConfigOCs *main, ConfigOCs *extra )
5189 {
5190         Entry *e = entry_alloc();
5191         CfEntryInfo *ce = ch_calloc( 1, sizeof(CfEntryInfo) );
5192         struct berval val;
5193         struct berval ad_name;
5194         AttributeDescription *ad = NULL;
5195         int rc;
5196         char *ptr;
5197         const char *text;
5198         Attribute *oc_at;
5199         struct berval pdn;
5200         ObjectClass *oc;
5201         CfEntryInfo *ceprev = NULL;
5202
5203         Debug( LDAP_DEBUG_TRACE, "config_build_entry: \"%s\"\n", rdn->bv_val, 0, 0);
5204         e->e_private = ce;
5205         ce->ce_entry = e;
5206         ce->ce_type = main->co_type;
5207         ce->ce_parent = parent;
5208         if ( parent ) {
5209                 pdn = parent->ce_entry->e_nname;
5210                 if ( parent->ce_kids )
5211                         for ( ceprev = parent->ce_kids; ceprev->ce_sibs &&
5212                                 ceprev->ce_type <= ce->ce_type;
5213                                 ceprev = ceprev->ce_sibs );
5214         } else {
5215                 BER_BVZERO( &pdn );
5216         }
5217
5218         ce->ce_private = c->private;
5219         ce->ce_be = c->be;
5220         ce->ce_bi = c->bi;
5221
5222         build_new_dn( &e->e_name, &pdn, rdn, NULL );
5223         ber_dupbv( &e->e_nname, &e->e_name );
5224
5225         attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5226                 main->co_name, NULL );
5227         if ( extra )
5228                 attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5229                         extra->co_name, NULL );
5230         ptr = strchr(rdn->bv_val, '=');
5231         ad_name.bv_val = rdn->bv_val;
5232         ad_name.bv_len = ptr - rdn->bv_val;
5233         rc = slap_bv2ad( &ad_name, &ad, &text );
5234         if ( rc ) {
5235                 return NULL;
5236         }
5237         val.bv_val = ptr+1;
5238         val.bv_len = rdn->bv_len - (val.bv_val - rdn->bv_val);
5239         attr_merge_normalize_one(e, ad, &val, NULL );
5240
5241         oc = main->co_oc;
5242         c->table = main->co_type;
5243         if ( oc->soc_required )
5244                 config_build_attrs( e, oc->soc_required, ad, main->co_table, c );
5245
5246         if ( oc->soc_allowed )
5247                 config_build_attrs( e, oc->soc_allowed, ad, main->co_table, c );
5248
5249         if ( extra ) {
5250                 oc = extra->co_oc;
5251                 c->table = extra->co_type;
5252                 if ( oc->soc_required )
5253                         config_build_attrs( e, oc->soc_required, ad, extra->co_table, c );
5254
5255                 if ( oc->soc_allowed )
5256                         config_build_attrs( e, oc->soc_allowed, ad, extra->co_table, c );
5257         }
5258
5259         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
5260         rc = structural_class(oc_at->a_vals, &oc, NULL, &text, c->cr_msg,
5261                 sizeof(c->cr_msg), op ? op->o_tmpmemctx : NULL );
5262         attr_merge_normalize_one(e, slap_schema.si_ad_structuralObjectClass, &oc->soc_cname, NULL );
5263         if ( op && !op->o_noop ) {
5264                 op->ora_e = e;
5265                 op->ora_modlist = NULL;
5266                 op->o_bd->be_add( op, rs );
5267                 if ( ( rs->sr_err != LDAP_SUCCESS ) 
5268                                 && (rs->sr_err != LDAP_ALREADY_EXISTS) ) {
5269                         return NULL;
5270                 }
5271         }
5272         if ( ceprev ) {
5273                 ce->ce_sibs = ceprev->ce_sibs;
5274                 ceprev->ce_sibs = ce;
5275         } else if ( parent ) {
5276                 ce->ce_sibs = parent->ce_kids;
5277                 parent->ce_kids = ce;
5278         }
5279
5280         return e;
5281 }
5282
5283 static int
5284 config_build_schema_inc( ConfigArgs *c, CfEntryInfo *ceparent,
5285         Operation *op, SlapReply *rs )
5286 {
5287         Entry *e;
5288         ConfigFile *cf = c->private;
5289         char *ptr;
5290         struct berval bv;
5291
5292         for (; cf; cf=cf->c_sibs, c->depth++) {
5293                 if ( !cf->c_at_head && !cf->c_cr_head && !cf->c_oc_head &&
5294                         !cf->c_om_head ) continue;
5295                 c->value_dn.bv_val = c->log;
5296                 LUTIL_SLASHPATH( cf->c_file.bv_val );
5297                 bv.bv_val = strrchr(cf->c_file.bv_val, LDAP_DIRSEP[0]);
5298                 if ( !bv.bv_val ) {
5299                         bv = cf->c_file;
5300                 } else {
5301                         bv.bv_val++;
5302                         bv.bv_len = cf->c_file.bv_len - (bv.bv_val - cf->c_file.bv_val);
5303                 }
5304                 ptr = strchr( bv.bv_val, '.' );
5305                 if ( ptr )
5306                         bv.bv_len = ptr - bv.bv_val;
5307                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=" SLAP_X_ORDERED_FMT, c->depth);
5308                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5309                         /* FIXME: how can indicate error? */
5310                         return -1;
5311                 }
5312                 strncpy( c->value_dn.bv_val + c->value_dn.bv_len, bv.bv_val,
5313                         bv.bv_len );
5314                 c->value_dn.bv_len += bv.bv_len;
5315                 c->value_dn.bv_val[c->value_dn.bv_len] ='\0';
5316
5317                 c->private = cf;
5318                 e = config_build_entry( op, rs, ceparent, c, &c->value_dn,
5319                         &CFOC_SCHEMA, NULL );
5320                 if ( !e ) {
5321                         return -1;
5322                 } else if ( e && cf->c_kids ) {
5323                         c->private = cf->c_kids;
5324                         config_build_schema_inc( c, e->e_private, op, rs );
5325                 }
5326         }
5327         return 0;
5328 }
5329
5330 #ifdef SLAPD_MODULES
5331
5332 static int
5333 config_build_modules( ConfigArgs *c, CfEntryInfo *ceparent,
5334         Operation *op, SlapReply *rs )
5335 {
5336         int i;
5337         ModPaths *mp;
5338
5339         for (i=0, mp=&modpaths; mp; mp=mp->mp_next, i++) {
5340                 if ( BER_BVISNULL( &mp->mp_path ) && !mp->mp_loads )
5341                         continue;
5342                 c->value_dn.bv_val = c->log;
5343                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=module" SLAP_X_ORDERED_FMT, i);
5344                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5345                         /* FIXME: how can indicate error? */
5346                         return -1;
5347                 }
5348                 c->private = mp;
5349                 if ( ! config_build_entry( op, rs, ceparent, c, &c->value_dn, &CFOC_MODULE, NULL )) {
5350                         return -1;
5351                 }
5352         }
5353         return 0;
5354 }
5355 #endif
5356
5357 static int
5358 config_check_schema(Operation *op, CfBackInfo *cfb)
5359 {
5360         struct berval schema_dn = BER_BVC(SCHEMA_RDN "," CONFIG_RDN);
5361         ConfigArgs c = {0};
5362         CfEntryInfo *ce, *last;
5363         Entry *e;
5364
5365         /* If there's no root entry, we must be in the midst of converting */
5366         if ( !cfb->cb_root )
5367                 return 0;
5368
5369         /* Make sure the main schema entry exists */
5370         ce = config_find_base( cfb->cb_root, &schema_dn, &last );
5371         if ( ce ) {
5372                 Attribute *a;
5373                 struct berval *bv;
5374
5375                 e = ce->ce_entry;
5376
5377                 /* Make sure it's up to date */
5378                 if ( cf_om_tail != om_sys_tail ) {
5379                         a = attr_find( e->e_attrs, cfAd_om );
5380                         if ( a ) {
5381                                 if ( a->a_nvals != a->a_vals )
5382                                         ber_bvarray_free( a->a_nvals );
5383                                 ber_bvarray_free( a->a_vals );
5384                                 a->a_vals = NULL;
5385                                 a->a_nvals = NULL;
5386                         }
5387                         oidm_unparse( &bv, NULL, NULL, 1 );
5388                         attr_merge_normalize( e, cfAd_om, bv, NULL );
5389                         ber_bvarray_free( bv );
5390                         cf_om_tail = om_sys_tail;
5391                 }
5392                 if ( cf_at_tail != at_sys_tail ) {
5393                         a = attr_find( e->e_attrs, cfAd_attr );
5394                         if ( a ) {
5395                                 if ( a->a_nvals != a->a_vals )
5396                                         ber_bvarray_free( a->a_nvals );
5397                                 ber_bvarray_free( a->a_vals );
5398                                 a->a_vals = NULL;
5399                                 a->a_nvals = NULL;
5400                         }
5401                         at_unparse( &bv, NULL, NULL, 1 );
5402                         attr_merge_normalize( e, cfAd_attr, bv, NULL );
5403                         ber_bvarray_free( bv );
5404                         cf_at_tail = at_sys_tail;
5405                 }
5406                 if ( cf_oc_tail != oc_sys_tail ) {
5407                         a = attr_find( e->e_attrs, cfAd_oc );
5408                         if ( a ) {
5409                                 if ( a->a_nvals != a->a_vals )
5410                                         ber_bvarray_free( a->a_nvals );
5411                                 ber_bvarray_free( a->a_vals );
5412                                 a->a_vals = NULL;
5413                                 a->a_nvals = NULL;
5414                         }
5415                         oc_unparse( &bv, NULL, NULL, 1 );
5416                         attr_merge_normalize( e, cfAd_oc, bv, NULL );
5417                         ber_bvarray_free( bv );
5418                         cf_oc_tail = oc_sys_tail;
5419                 }
5420         } else {
5421                 SlapReply rs = {REP_RESULT};
5422                 c.private = NULL;
5423                 e = config_build_entry( op, &rs, cfb->cb_root, &c, &schema_rdn,
5424                         &CFOC_SCHEMA, NULL );
5425                 if ( !e ) {
5426                         return -1;
5427                 }
5428                 ce = e->e_private;
5429                 ce->ce_private = cfb->cb_config;
5430                 cf_at_tail = at_sys_tail;
5431                 cf_oc_tail = oc_sys_tail;
5432                 cf_om_tail = om_sys_tail;
5433         }
5434         return 0;
5435 }
5436
5437 static const char *defacl[] = {
5438         NULL, "to", "*", "by", "*", "none", NULL
5439 };
5440
5441 static int
5442 config_back_db_open( BackendDB *be, ConfigReply *cr )
5443 {
5444         CfBackInfo *cfb = be->be_private;
5445         struct berval rdn;
5446         Entry *e, *parent;
5447         CfEntryInfo *ce, *ceparent;
5448         int i, unsupp = 0;
5449         BackendInfo *bi;
5450         ConfigArgs c;
5451         Connection conn = {0};
5452         OperationBuffer opbuf;
5453         Operation *op;
5454         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
5455         SlapReply rs = {REP_RESULT};
5456         void *thrctx = NULL;
5457
5458         Debug( LDAP_DEBUG_TRACE, "config_back_db_open\n", 0, 0, 0);
5459
5460         /* If we have no explicitly configured ACLs, don't just use
5461          * the global ACLs. Explicitly deny access to everything.
5462          */
5463         if ( frontendDB->be_acl && be->be_acl == frontendDB->be_acl ) {
5464                 parse_acl(be, "config_back_db_open", 0, 6, (char **)defacl, 0 );
5465         }
5466
5467         thrctx = ldap_pvt_thread_pool_context();
5468         connection_fake_init( &conn, &opbuf, thrctx );
5469         op = &opbuf.ob_op;
5470
5471         op->o_tag = LDAP_REQ_ADD;
5472         op->o_callback = &cb;
5473         op->o_bd = &cfb->cb_db;
5474         op->o_dn = op->o_bd->be_rootdn;
5475         op->o_ndn = op->o_bd->be_rootndn;
5476
5477         if ( !cfb->cb_use_ldif ) {
5478                 op->o_noop = 1;
5479         }
5480
5481         /* If we read the config from back-ldif, do some quick sanity checks */
5482         if ( cfb->cb_got_ldif ) {
5483                 return config_check_schema( op, cfb );
5484         }
5485
5486         /* create root of tree */
5487         rdn = config_rdn;
5488         c.private = cfb->cb_config;
5489         c.be = frontendDB;
5490         e = config_build_entry( op, &rs, NULL, &c, &rdn, &CFOC_GLOBAL, NULL );
5491         if ( !e ) {
5492                 return -1;
5493         }
5494         ce = e->e_private;
5495         cfb->cb_root = ce;
5496
5497         parent = e;
5498         ceparent = ce;
5499
5500 #ifdef SLAPD_MODULES
5501         /* Create Module nodes... */
5502         if ( modpaths.mp_loads ) {
5503                 if ( config_build_modules( &c, ceparent, op, &rs ) ){
5504                         return -1;
5505                 }
5506         }
5507 #endif
5508
5509         /* Create schema nodes... cn=schema will contain the hardcoded core
5510          * schema, read-only. Child objects will contain runtime loaded schema
5511          * files.
5512          */
5513         rdn = schema_rdn;
5514         c.private = NULL;
5515         e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_SCHEMA, NULL );
5516         if ( !e ) {
5517                 return -1;
5518         }
5519         ce = e->e_private;
5520         ce->ce_private = cfb->cb_config;
5521         cf_at_tail = at_sys_tail;
5522         cf_oc_tail = oc_sys_tail;
5523         cf_om_tail = om_sys_tail;
5524
5525         /* Create schema nodes for included schema... */
5526         if ( cfb->cb_config->c_kids ) {
5527                 c.depth = 0;
5528                 c.private = cfb->cb_config->c_kids;
5529                 if (config_build_schema_inc( &c, ce, op, &rs )) {
5530                         return -1;
5531                 }
5532         }
5533
5534         /* Create backend nodes. Skip if they don't provide a cf_table.
5535          * There usually aren't any of these.
5536          */
5537         
5538         c.line = 0;
5539         LDAP_STAILQ_FOREACH( bi, &backendInfo, bi_next) {
5540                 if (!bi->bi_cf_ocs) {
5541                         /* If it only supports the old config mech, complain. */
5542                         if ( bi->bi_config ) {
5543                                 Debug( LDAP_DEBUG_ANY,
5544                                         "WARNING: No dynamic config support for backend %s.\n",
5545                                         bi->bi_type, 0, 0 );
5546                                 unsupp++;
5547                         }
5548                         continue;
5549                 }
5550                 if (!bi->bi_private) continue;
5551
5552                 rdn.bv_val = c.log;
5553                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5554                         "%s=%s", cfAd_backend->ad_cname.bv_val, bi->bi_type);
5555                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5556                         /* FIXME: holler ... */ ;
5557                 }
5558                 c.bi = bi;
5559                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_BACKEND,
5560                         bi->bi_cf_ocs );
5561                 if ( !e ) {
5562                         return -1;
5563                 }
5564         }
5565
5566         /* Create database nodes... */
5567         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
5568         LDAP_STAILQ_NEXT(frontendDB, be_next) = LDAP_STAILQ_FIRST(&backendDB);
5569         for ( i = -1, be = frontendDB ; be;
5570                 i++, be = LDAP_STAILQ_NEXT( be, be_next )) {
5571                 slap_overinfo *oi = NULL;
5572
5573                 if ( overlay_is_over( be )) {
5574                         oi = be->bd_info->bi_private;
5575                         bi = oi->oi_orig;
5576                 } else {
5577                         bi = be->bd_info;
5578                 }
5579
5580                 /* If this backend supports the old config mechanism, but not
5581                  * the new mech, complain.
5582                  */
5583                 if ( !be->be_cf_ocs && bi->bi_db_config ) {
5584                         Debug( LDAP_DEBUG_ANY,
5585                                 "WARNING: No dynamic config support for database %s.\n",
5586                                 bi->bi_type, 0, 0 );
5587                         unsupp++;
5588                 }
5589                 rdn.bv_val = c.log;
5590                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5591                         "%s=" SLAP_X_ORDERED_FMT "%s", cfAd_database->ad_cname.bv_val,
5592                         i, bi->bi_type);
5593                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5594                         /* FIXME: holler ... */ ;
5595                 }
5596                 c.be = be;
5597                 c.bi = bi;
5598                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_DATABASE,
5599                         be->be_cf_ocs );
5600                 if ( !e ) {
5601                         return -1;
5602                 }
5603                 ce = e->e_private;
5604                 if ( be->be_cf_ocs && be->be_cf_ocs->co_cfadd )
5605                         be->be_cf_ocs->co_cfadd( op, &rs, e, &c );
5606                 /* Iterate through overlays */
5607                 if ( oi ) {
5608                         slap_overinst *on;
5609                         Entry *oe;
5610                         int j;
5611
5612                         for (j=0,on=oi->oi_list; on; j++,on=on->on_next) {
5613                                 if ( on->on_bi.bi_db_config && !on->on_bi.bi_cf_ocs ) {
5614                                         Debug( LDAP_DEBUG_ANY,
5615                                                 "WARNING: No dynamic config support for overlay %s.\n",
5616                                                 on->on_bi.bi_type, 0, 0 );
5617                                         unsupp++;
5618                                 }
5619                                 rdn.bv_val = c.log;
5620                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5621                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5622                                         cfAd_overlay->ad_cname.bv_val, j, on->on_bi.bi_type );
5623                                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5624                                         /* FIXME: holler ... */ ;
5625                                 }
5626                                 c.be = be;
5627                                 c.bi = &on->on_bi;
5628                                 oe = config_build_entry( op, &rs, ce, &c, &rdn,
5629                                         &CFOC_OVERLAY, c.bi->bi_cf_ocs );
5630                                 if ( !oe ) {
5631                                         return -1;
5632                                 }
5633                                 if ( c.bi->bi_cf_ocs && c.bi->bi_cf_ocs->co_cfadd )
5634                                         c.bi->bi_cf_ocs->co_cfadd( op, &rs, oe, &c );
5635                         }
5636                 }
5637         }
5638         if ( thrctx )
5639                 ldap_pvt_thread_pool_context_reset( thrctx );
5640
5641         if ( unsupp  && cfb->cb_use_ldif ) {
5642                 Debug( LDAP_DEBUG_ANY, "\nWARNING: The converted cn=config "
5643                         "directory is incomplete and may not work.\n\n", 0, 0, 0 );
5644         }
5645
5646         return 0;
5647 }
5648
5649 static void
5650 cfb_free_cffile( ConfigFile *cf )
5651 {
5652         ConfigFile *next;
5653
5654         for (; cf; cf=next) {
5655                 next = cf->c_sibs;
5656                 if ( cf->c_kids )
5657                         cfb_free_cffile( cf->c_kids );
5658                 ch_free( cf->c_file.bv_val );
5659                 ber_bvarray_free( cf->c_dseFiles );
5660                 ch_free( cf );
5661         }
5662 }
5663
5664 static void
5665 cfb_free_entries( CfEntryInfo *ce )
5666 {
5667         CfEntryInfo *next;
5668
5669         for (; ce; ce=next) {
5670                 next = ce->ce_sibs;
5671                 if ( ce->ce_kids )
5672                         cfb_free_entries( ce->ce_kids );
5673                 ce->ce_entry->e_private = NULL;
5674                 entry_free( ce->ce_entry );
5675                 ch_free( ce );
5676         }
5677 }
5678
5679 static int
5680 config_back_db_close( BackendDB *be, ConfigReply *cr )
5681 {
5682         CfBackInfo *cfb = be->be_private;
5683
5684         cfb_free_entries( cfb->cb_root );
5685         cfb->cb_root = NULL;
5686
5687         if ( cfb->cb_db.bd_info ) {
5688                 backend_shutdown( &cfb->cb_db );
5689         }
5690
5691         return 0;
5692 }
5693
5694 static int
5695 config_back_db_destroy( BackendDB *be, ConfigReply *cr )
5696 {
5697         CfBackInfo *cfb = be->be_private;
5698
5699         cfb_free_cffile( cfb->cb_config );
5700
5701         ch_free( cfdir.bv_val );
5702
5703         avl_free( CfOcTree, NULL );
5704
5705         if ( cfb->cb_db.bd_info ) {
5706                 cfb->cb_db.be_suffix = NULL;
5707                 cfb->cb_db.be_nsuffix = NULL;
5708                 BER_BVZERO( &cfb->cb_db.be_rootdn );
5709                 BER_BVZERO( &cfb->cb_db.be_rootndn );
5710
5711                 backend_destroy_one( &cfb->cb_db, 0 );
5712         }
5713
5714         loglevel_destroy();
5715
5716         return 0;
5717 }
5718
5719 static int
5720 config_back_db_init( BackendDB *be, ConfigReply* cr )
5721 {
5722         struct berval dn;
5723         CfBackInfo *cfb;
5724
5725         cfb = &cfBackInfo;
5726         cfb->cb_config = ch_calloc( 1, sizeof(ConfigFile));
5727         cfn = cfb->cb_config;
5728         be->be_private = cfb;
5729
5730         ber_dupbv( &be->be_rootdn, &config_rdn );
5731         ber_dupbv( &be->be_rootndn, &be->be_rootdn );
5732         ber_dupbv( &dn, &be->be_rootdn );
5733         ber_bvarray_add( &be->be_suffix, &dn );
5734         ber_dupbv( &dn, &be->be_rootdn );
5735         ber_bvarray_add( &be->be_nsuffix, &dn );
5736
5737         /* Hide from namingContexts */
5738         SLAP_BFLAGS(be) |= SLAP_BFLAG_CONFIG;
5739
5740         return 0;
5741 }
5742
5743 static int
5744 config_back_destroy( BackendInfo *bi )
5745 {
5746         ldif_must_b64_encode_release();
5747         return 0;
5748 }
5749
5750 static int
5751 config_tool_entry_open( BackendDB *be, int mode )
5752 {
5753         CfBackInfo *cfb = be->be_private;
5754         BackendInfo *bi = cfb->cb_db.bd_info;
5755
5756         if ( bi && bi->bi_tool_entry_open )
5757                 return bi->bi_tool_entry_open( &cfb->cb_db, mode );
5758         else
5759                 return -1;
5760         
5761 }
5762
5763 static int
5764 config_tool_entry_close( BackendDB *be )
5765 {
5766         CfBackInfo *cfb = be->be_private;
5767         BackendInfo *bi = cfb->cb_db.bd_info;
5768
5769         if ( bi && bi->bi_tool_entry_close )
5770                 return bi->bi_tool_entry_close( &cfb->cb_db );
5771         else
5772                 return -1;
5773 }
5774
5775 static ID
5776 config_tool_entry_first( BackendDB *be )
5777 {
5778         CfBackInfo *cfb = be->be_private;
5779         BackendInfo *bi = cfb->cb_db.bd_info;
5780
5781         if ( bi && bi->bi_tool_entry_first )
5782                 return bi->bi_tool_entry_first( &cfb->cb_db );
5783         else
5784                 return NOID;
5785 }
5786
5787 static ID
5788 config_tool_entry_next( BackendDB *be )
5789 {
5790         CfBackInfo *cfb = be->be_private;
5791         BackendInfo *bi = cfb->cb_db.bd_info;
5792
5793         if ( bi && bi->bi_tool_entry_next )
5794                 return bi->bi_tool_entry_next( &cfb->cb_db );
5795         else
5796                 return NOID;
5797 }
5798
5799 static Entry *
5800 config_tool_entry_get( BackendDB *be, ID id )
5801 {
5802         CfBackInfo *cfb = be->be_private;
5803         BackendInfo *bi = cfb->cb_db.bd_info;
5804
5805         if ( bi && bi->bi_tool_entry_get )
5806                 return bi->bi_tool_entry_get( &cfb->cb_db, id );
5807         else
5808                 return NULL;
5809 }
5810
5811 static int entry_put_got_frontend=0;
5812 static int entry_put_got_config=0;
5813 static ID
5814 config_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
5815 {
5816         CfBackInfo *cfb = be->be_private;
5817         BackendInfo *bi = cfb->cb_db.bd_info;
5818         int rc;
5819         struct berval rdn, vals[ 2 ];
5820         ConfigArgs ca;
5821         OperationBuffer opbuf;
5822         Entry *ce;
5823         Connection conn = {0};
5824         Operation *op = NULL;
5825         void *thrctx;
5826
5827         /* Create entry for frontend database if it does not exist already */
5828         if ( !entry_put_got_frontend ) {
5829                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase", 
5830                                 STRLENOF( "olcDatabase" ))) {
5831                         if ( strncmp( e->e_nname.bv_val + 
5832                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
5833                                         STRLENOF( "={-1}frontend" )) && 
5834                                         strncmp( e->e_nname.bv_val + 
5835                                         STRLENOF( "olcDatabase" ), "=frontend",
5836                                         STRLENOF( "=frontend" ))) {
5837                                 vals[1].bv_len = 0;
5838                                 vals[1].bv_val = NULL;
5839                                 memset( &ca, 0, sizeof(ConfigArgs));
5840                                 ca.be = frontendDB;
5841                                 ca.bi = frontendDB->bd_info;
5842                                 ca.be->be_cf_ocs = &CFOC_FRONTEND;
5843                                 rdn.bv_val = ca.log;
5844                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5845                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5846                                         cfAd_database->ad_cname.bv_val, -1,
5847                                         ca.bi->bi_type);
5848                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn,
5849                                                 &CFOC_DATABASE, ca.be->be_cf_ocs );
5850                                 thrctx = ldap_pvt_thread_pool_context();
5851                                 connection_fake_init2( &conn, &opbuf, thrctx,0 );
5852                                 op = &opbuf.ob_op;
5853                                 op->o_bd = &cfb->cb_db;
5854                                 op->o_tag = LDAP_REQ_ADD;
5855                                 op->ora_e = ce;
5856                                 op->o_dn = be->be_rootdn;
5857                                 op->o_ndn = be->be_rootndn;
5858                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5859                                 if ( rc != LDAP_SUCCESS ) {
5860                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5861                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5862                                         return NOID;
5863                                 }
5864
5865                                 if ( ce && bi && bi->bi_tool_entry_put && 
5866                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5867                                         entry_put_got_frontend++;
5868                                 } else {
5869                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5870                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5871                                         return NOID;
5872                                 }
5873                         } else {
5874                                 entry_put_got_frontend++;
5875                         }
5876                 }
5877         }
5878         /* Create entry for config database if it does not exist already */
5879         if ( !entry_put_got_config ) {
5880                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase",
5881                                 STRLENOF( "olcDatabase" ))) {
5882                         if ( strncmp( e->e_nname.bv_val +
5883                                         STRLENOF( "olcDatabase" ), "={0}config",
5884                                         STRLENOF( "={0}config" )) &&
5885                                         strncmp( e->e_nname.bv_val +
5886                                         STRLENOF( "olcDatabase" ), "=config",
5887                                         STRLENOF( "=config" )) ) {
5888                                 vals[1].bv_len = 0;
5889                                 vals[1].bv_val = NULL;
5890                                 memset( &ca, 0, sizeof(ConfigArgs));
5891                                 ca.be = LDAP_STAILQ_FIRST( &backendDB );
5892                                 ca.bi = ca.be->bd_info;
5893                                 rdn.bv_val = ca.log;
5894                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5895                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5896                                         cfAd_database->ad_cname.bv_val, 0,
5897                                         ca.bi->bi_type);
5898                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn, &CFOC_DATABASE,
5899                                                 ca.be->be_cf_ocs );
5900                                 if ( ! op ) {
5901                                         thrctx = ldap_pvt_thread_pool_context();
5902                                         connection_fake_init2( &conn, &opbuf, thrctx,0 );
5903                                         op = &opbuf.ob_op;
5904                                         op->o_bd = &cfb->cb_db;
5905                                         op->o_tag = LDAP_REQ_ADD;
5906                                         op->o_dn = be->be_rootdn;
5907                                         op->o_ndn = be->be_rootndn;
5908                                 }
5909                                 op->ora_e = ce;
5910                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5911                                 if ( rc != LDAP_SUCCESS ) {
5912                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5913                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5914                                         return NOID;
5915                                 }
5916                                 if (ce && bi && bi->bi_tool_entry_put &&
5917                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5918                                         entry_put_got_config++;
5919                                 } else {
5920                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5921                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5922                                         return NOID;
5923                                 }
5924                         } else {
5925                                 entry_put_got_config++;
5926                         }
5927                 }
5928         }
5929         if ( bi && bi->bi_tool_entry_put &&
5930                 config_add_internal( cfb, e, &ca, NULL, NULL, NULL ) == 0 )
5931                 return bi->bi_tool_entry_put( &cfb->cb_db, e, text );
5932         else
5933                 return NOID;
5934 }
5935
5936 static struct {
5937         char *name;
5938         AttributeDescription **desc;
5939 } ads[] = {
5940         { "attribute", &cfAd_attr },
5941         { "backend", &cfAd_backend },
5942         { "database", &cfAd_database },
5943         { "include", &cfAd_include },
5944         { "objectclass", &cfAd_oc },
5945         { "objectidentifier", &cfAd_om },
5946         { "overlay", &cfAd_overlay },
5947         { NULL, NULL }
5948 };
5949
5950 /* Notes:
5951  *   add / delete: all types that may be added or deleted must use an
5952  * X-ORDERED attributeType for their RDN. Adding and deleting entries
5953  * should automatically renumber the index of any siblings as needed,
5954  * so that no gaps in the numbering sequence exist after the add/delete
5955  * is completed.
5956  *   What can be added:
5957  *     schema objects
5958  *     backend objects for backend-specific config directives
5959  *     database objects
5960  *     overlay objects
5961  *
5962  *   delete: probably no support this time around.
5963  *
5964  *   modrdn: generally not done. Will be invoked automatically by add/
5965  * delete to update numbering sequence. Perform as an explicit operation
5966  * so that the renumbering effect may be replicated. Subtree rename must
5967  * be supported, since renumbering a database will affect all its child
5968  * overlays.
5969  *
5970  *  modify: must be fully supported. 
5971  */
5972
5973 int
5974 config_back_initialize( BackendInfo *bi )
5975 {
5976         ConfigTable             *ct = config_back_cf_table;
5977         ConfigArgs ca;
5978         char                    *argv[4];
5979         int                     i;
5980         AttributeDescription    *ad = NULL;
5981         const char              *text;
5982         static char             *controls[] = {
5983                 LDAP_CONTROL_MANAGEDSAIT,
5984                 NULL
5985         };
5986
5987         /* Make sure we don't exceed the bits reserved for userland */
5988         config_check_userland( CFG_LAST );
5989
5990         bi->bi_controls = controls;
5991
5992         bi->bi_open = 0;
5993         bi->bi_close = 0;
5994         bi->bi_config = 0;
5995         bi->bi_destroy = config_back_destroy;
5996
5997         bi->bi_db_init = config_back_db_init;
5998         bi->bi_db_config = 0;
5999         bi->bi_db_open = config_back_db_open;
6000         bi->bi_db_close = config_back_db_close;
6001         bi->bi_db_destroy = config_back_db_destroy;
6002
6003         bi->bi_op_bind = config_back_bind;
6004         bi->bi_op_unbind = 0;
6005         bi->bi_op_search = config_back_search;
6006         bi->bi_op_compare = 0;
6007         bi->bi_op_modify = config_back_modify;
6008         bi->bi_op_modrdn = config_back_modrdn;
6009         bi->bi_op_add = config_back_add;
6010         bi->bi_op_delete = config_back_delete;
6011         bi->bi_op_abandon = 0;
6012
6013         bi->bi_extended = 0;
6014
6015         bi->bi_chk_referrals = 0;
6016
6017         bi->bi_access_allowed = slap_access_allowed;
6018
6019         bi->bi_connection_init = 0;
6020         bi->bi_connection_destroy = 0;
6021
6022         bi->bi_entry_release_rw = config_entry_release;
6023         bi->bi_entry_get_rw = config_back_entry_get;
6024
6025         bi->bi_tool_entry_open = config_tool_entry_open;
6026         bi->bi_tool_entry_close = config_tool_entry_close;
6027         bi->bi_tool_entry_first = config_tool_entry_first;
6028         bi->bi_tool_entry_next = config_tool_entry_next;
6029         bi->bi_tool_entry_get = config_tool_entry_get;
6030         bi->bi_tool_entry_put = config_tool_entry_put;
6031
6032         ca.argv = argv;
6033         argv[ 0 ] = "slapd";
6034         ca.argv = argv;
6035         ca.argc = 3;
6036         ca.fname = argv[0];
6037
6038         argv[3] = NULL;
6039         for (i=0; OidMacros[i].name; i++ ) {
6040                 argv[1] = OidMacros[i].name;
6041                 argv[2] = OidMacros[i].oid;
6042                 parse_oidm( &ca, 0, NULL );
6043         }
6044
6045         bi->bi_cf_ocs = cf_ocs;
6046
6047         i = config_register_schema( ct, cf_ocs );
6048         if ( i ) return i;
6049
6050         /* setup olcRootPW to be base64-encoded when written in LDIF form;
6051          * basically, we don't care if it fails */
6052         i = slap_str2ad( "olcRootPW", &ad, &text );
6053         if ( i ) {
6054                 Debug( LDAP_DEBUG_ANY, "config_back_initialize: "
6055                         "warning, unable to get \"olcRootPW\" "
6056                         "attribute description: %d: %s\n",
6057                         i, text, 0 );
6058         } else {
6059                 (void)ldif_must_b64_encode_register( ad->ad_cname.bv_val,
6060                         ad->ad_type->sat_oid );
6061         }
6062
6063         /* set up the notable AttributeDescriptions */
6064         i = 0;
6065         for (;ct->name;ct++) {
6066                 if (strcmp(ct->name, ads[i].name)) continue;
6067                 *ads[i].desc = ct->ad;
6068                 i++;
6069                 if (!ads[i].name) break;
6070         }
6071
6072         return 0;
6073 }
6074