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