]> git.sur5r.net Git - openldap/blob - servers/slapd/bconfig.c
Sync with HEAD for OL 2.4.5
[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                                         Debug( LDAP_DEBUG_CONFIG,
1512                                                 "%s: SID=%d\n",
1513                                                 c->log, slap_serverID, 0 );
1514                                 }
1515                                 si->si_next = NULL;
1516                                 si->si_num = num;
1517                                 for ( sip = &sid_list; *sip; sip = &(*sip)->si_next );
1518                                 *sip = si;
1519
1520                                 if (( slapMode & SLAP_SERVER_MODE ) && c->argc > 2 ) {
1521                                         /* If hostname is empty, or is localhost, or matches
1522                                          * our hostname, this serverID refers to this host.
1523                                          * Compare it against listeners and ports.
1524                                          */
1525                                         if ( !lud->lud_host || !lud->lud_host[0] ||
1526                                                 !strncasecmp("localhost", lud->lud_host,
1527                                                         STRLENOF("localhost")) ||
1528                                                 !strcasecmp( global_host, lud->lud_host )) {
1529                                                 Listener **l = slapd_get_listeners();
1530                                                 int i;
1531
1532                                                 for ( i=0; l[i]; i++ ) {
1533                                                         LDAPURLDesc *lu2;
1534                                                         int isMe = 0;
1535                                                         ldap_url_parse( l[i]->sl_url.bv_val, &lu2 );
1536                                                         do {
1537                                                                 if ( strcasecmp( lud->lud_scheme,
1538                                                                         lu2->lud_scheme ))
1539                                                                         break;
1540                                                                 if ( lud->lud_port != lu2->lud_port )
1541                                                                         break;
1542                                                                 /* Listener on ANY address */
1543                                                                 if ( !lu2->lud_host || !lu2->lud_host[0] ) {
1544                                                                         isMe = 1;
1545                                                                         break;
1546                                                                 }
1547                                                                 /* URL on ANY address */
1548                                                                 if ( !lud->lud_host || !lud->lud_host[0] ) {
1549                                                                         isMe = 1;
1550                                                                         break;
1551                                                                 }
1552                                                                 /* Listener has specific host, must
1553                                                                  * match it
1554                                                                  */
1555                                                                 if ( !strcasecmp( lud->lud_host,
1556                                                                         lu2->lud_host )) {
1557                                                                         isMe = 1;
1558                                                                         break;
1559                                                                 }
1560                                                         } while(0);
1561                                                         ldap_free_urldesc( lu2 );
1562                                                         if ( isMe ) {
1563                                                                 slap_serverID = si->si_num;
1564                                                                 Debug( LDAP_DEBUG_CONFIG,
1565                                                                         "%s: SID=%d (listener=%s)\n",
1566                                                                         c->log, slap_serverID,
1567                                                                         l[i]->sl_url.bv_val );
1568                                                                 break;
1569                                                         }
1570                                                 }
1571                                         }
1572                                 }
1573                                 if ( c->argc > 2 )
1574                                         ldap_free_urldesc( lud );
1575                         }
1576                         break;
1577                 case CFG_LOGFILE: {
1578                                 FILE *logfile;
1579                                 if ( logfileName ) ch_free( logfileName );
1580                                 logfileName = c->value_string;
1581                                 logfile = fopen(logfileName, "w");
1582                                 if(logfile) lutil_debug_file(logfile);
1583                         } break;
1584
1585                 case CFG_LASTMOD:
1586                         if(SLAP_NOLASTMODCMD(c->be)) {
1587                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> not available for %s database",
1588                                         c->argv[0], c->be->bd_info->bi_type );
1589                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1590                                         c->log, c->cr_msg, 0 );
1591                                 return(1);
1592                         }
1593                         if(c->value_int)
1594                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_NOLASTMOD;
1595                         else
1596                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NOLASTMOD;
1597                         break;
1598
1599                 case CFG_MIRRORMODE:
1600                         if(!SLAP_SHADOW(c->be)) {
1601                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database is not a shadow",
1602                                         c->argv[0] );
1603                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1604                                         c->log, c->cr_msg, 0 );
1605                                 return(1);
1606                         }
1607                         if(c->value_int)
1608                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_SINGLE_SHADOW;
1609                         else
1610                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_SINGLE_SHADOW;
1611                         break;
1612
1613                 case CFG_MONITORING:
1614                         if(c->value_int)
1615                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_MONITORING;
1616                         else
1617                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_MONITORING;
1618                         break;
1619
1620                 case CFG_HIDDEN:
1621                         if (c->value_int)
1622                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_HIDDEN;
1623                         else
1624                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_HIDDEN;
1625                         break;
1626
1627                 case CFG_SSTR_IF_MAX:
1628                         if (c->value_int < index_substr_if_minlen) {
1629                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1630                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1631                                         c->log, c->cr_msg, c->value_int );
1632                                 return(1);
1633                         }
1634                         index_substr_if_maxlen = c->value_int;
1635                         break;
1636
1637                 case CFG_SSTR_IF_MIN:
1638                         if (c->value_int > index_substr_if_maxlen) {
1639                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1640                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1641                                         c->log, c->cr_msg, c->value_int );
1642                                 return(1);
1643                         }
1644                         index_substr_if_minlen = c->value_int;
1645                         break;
1646
1647 #ifdef SLAPD_MODULES
1648                 case CFG_MODLOAD:
1649                         /* If we're just adding a module on an existing modpath,
1650                          * make sure we've selected the current path.
1651                          */
1652                         if ( c->op == LDAP_MOD_ADD && c->private && modcur != c->private ) {
1653                                 modcur = c->private;
1654                                 /* This should never fail */
1655                                 if ( module_path( modcur->mp_path.bv_val )) {
1656                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> module path no longer valid",
1657                                                 c->argv[0] );
1658                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1659                                                 c->log, c->cr_msg, modcur->mp_path.bv_val );
1660                                         return(1);
1661                                 }
1662                         }
1663                         if(module_load(c->argv[1], c->argc - 2, (c->argc > 2) ? c->argv + 2 : NULL))
1664                                 return(1);
1665                         /* Record this load on the current path */
1666                         {
1667                                 struct berval bv;
1668                                 char *ptr;
1669                                 if ( c->op == SLAP_CONFIG_ADD ) {
1670                                         ptr = c->line + STRLENOF("moduleload");
1671                                         while (!isspace((unsigned char) *ptr)) ptr++;
1672                                         while (isspace((unsigned char) *ptr)) ptr++;
1673                                 } else {
1674                                         ptr = c->line;
1675                                 }
1676                                 ber_str2bv(ptr, 0, 1, &bv);
1677                                 ber_bvarray_add( &modcur->mp_loads, &bv );
1678                         }
1679                         /* Check for any new hardcoded schema */
1680                         if ( c->op == LDAP_MOD_ADD && CONFIG_ONLINE_ADD( c )) {
1681                                 config_check_schema( NULL, &cfBackInfo );
1682                         }
1683                         break;
1684
1685                 case CFG_MODPATH:
1686                         if(module_path(c->argv[1])) return(1);
1687                         /* Record which path was used with each module */
1688                         {
1689                                 ModPaths *mp;
1690
1691                                 if (!modpaths.mp_loads) {
1692                                         mp = &modpaths;
1693                                 } else {
1694                                         mp = ch_malloc( sizeof( ModPaths ));
1695                                         modlast->mp_next = mp;
1696                                 }
1697                                 ber_str2bv(c->argv[1], 0, 1, &mp->mp_path);
1698                                 mp->mp_next = NULL;
1699                                 mp->mp_loads = NULL;
1700                                 modlast = mp;
1701                                 c->private = mp;
1702                                 modcur = mp;
1703                         }
1704                         
1705                         break;
1706 #endif
1707
1708 #ifdef LDAP_SLAPI
1709                 case CFG_PLUGIN:
1710                         if(slapi_int_read_config(c->be, c->fname, c->lineno, c->argc, c->argv) != LDAP_SUCCESS)
1711                                 return(1);
1712                         slapi_plugins_used++;
1713                         break;
1714 #endif
1715
1716 #ifdef SLAP_AUTH_REWRITE
1717                 case CFG_REWRITE: {
1718                         struct berval bv;
1719                         char *line;
1720                         
1721                         if(slap_sasl_rewrite_config(c->fname, c->lineno, c->argc, c->argv))
1722                                 return(1);
1723
1724                         if ( c->argc > 1 ) {
1725                                 char    *s;
1726
1727                                 /* quote all args but the first */
1728                                 line = ldap_charray2str( c->argv, "\" \"" );
1729                                 ber_str2bv( line, 0, 0, &bv );
1730                                 s = ber_bvchr( &bv, '"' );
1731                                 assert( s != NULL );
1732                                 /* move the trailing quote of argv[0] to the end */
1733                                 AC_MEMCPY( s, s + 1, bv.bv_len - ( s - bv.bv_val ) );
1734                                 bv.bv_val[ bv.bv_len - 1 ] = '"';
1735
1736                         } else {
1737                                 ber_str2bv( c->argv[ 0 ], 0, 1, &bv );
1738                         }
1739                         
1740                         ber_bvarray_add( &authz_rewrites, &bv );
1741                         }
1742                         break;
1743 #endif
1744
1745
1746                 default:
1747                         Debug( LDAP_DEBUG_ANY,
1748                                 "%s: unknown CFG_TYPE %d.\n",
1749                                 c->log, c->type, 0 );
1750                         return 1;
1751
1752         }
1753         return(0);
1754 }
1755
1756
1757 static int
1758 config_fname(ConfigArgs *c) {
1759         if(c->op == SLAP_CONFIG_EMIT) {
1760                 if (c->private) {
1761                         ConfigFile *cf = c->private;
1762                         value_add_one( &c->rvalue_vals, &cf->c_file );
1763                         return 0;
1764                 }
1765                 return 1;
1766         }
1767         return(0);
1768 }
1769
1770 static int
1771 config_cfdir(ConfigArgs *c) {
1772         if(c->op == SLAP_CONFIG_EMIT) {
1773                 if ( !BER_BVISEMPTY( &cfdir )) {
1774                         value_add_one( &c->rvalue_vals, &cfdir );
1775                         return 0;
1776                 }
1777                 return 1;
1778         }
1779         return(0);
1780 }
1781
1782 static int
1783 config_search_base(ConfigArgs *c) {
1784         if(c->op == SLAP_CONFIG_EMIT) {
1785                 int rc = 1;
1786                 if (!BER_BVISEMPTY(&default_search_base)) {
1787                         value_add_one(&c->rvalue_vals, &default_search_base);
1788                         value_add_one(&c->rvalue_nvals, &default_search_nbase);
1789                         rc = 0;
1790                 }
1791                 return rc;
1792         } else if( c->op == LDAP_MOD_DELETE ) {
1793                 ch_free( default_search_base.bv_val );
1794                 ch_free( default_search_nbase.bv_val );
1795                 BER_BVZERO( &default_search_base );
1796                 BER_BVZERO( &default_search_nbase );
1797                 return 0;
1798         }
1799
1800         if(c->bi || c->be != frontendDB) {
1801                 Debug(LDAP_DEBUG_ANY, "%s: defaultSearchBase line must appear "
1802                         "prior to any backend or database definition\n",
1803                         c->log, 0, 0);
1804                 return(1);
1805         }
1806
1807         if(default_search_nbase.bv_len) {
1808                 free(default_search_base.bv_val);
1809                 free(default_search_nbase.bv_val);
1810         }
1811
1812         default_search_base = c->value_dn;
1813         default_search_nbase = c->value_ndn;
1814         return(0);
1815 }
1816
1817 static int
1818 config_passwd_hash(ConfigArgs *c) {
1819         int i;
1820         if (c->op == SLAP_CONFIG_EMIT) {
1821                 struct berval bv;
1822                 for (i=0; default_passwd_hash && default_passwd_hash[i]; i++) {
1823                         ber_str2bv(default_passwd_hash[i], 0, 0, &bv);
1824                         value_add_one(&c->rvalue_vals, &bv);
1825                 }
1826                 return i ? 0 : 1;
1827         } else if ( c->op == LDAP_MOD_DELETE ) {
1828                 if ( c->valx < 0 ) {
1829                         ldap_charray_free( default_passwd_hash );
1830                         default_passwd_hash = NULL;
1831                 } else {
1832                         i = c->valx;
1833                         ch_free( default_passwd_hash[i] );
1834                         for (; default_passwd_hash[i]; i++ )
1835                                 default_passwd_hash[i] = default_passwd_hash[i+1];
1836                 }
1837                 return 0;
1838         }
1839         if(default_passwd_hash) {
1840                 Debug(LDAP_DEBUG_ANY, "%s: "
1841                         "already set default password_hash\n",
1842                         c->log, 0, 0);
1843                 return(1);
1844         }
1845         for(i = 1; i < c->argc; i++) {
1846                 if(!lutil_passwd_scheme(c->argv[i])) {
1847                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> scheme not available", c->argv[0] );
1848                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1849                                 c->log, c->cr_msg, c->argv[i]);
1850                 } else {
1851                         ldap_charray_add(&default_passwd_hash, c->argv[i]);
1852                 }
1853                 if(!default_passwd_hash) {
1854                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> no valid hashes found", c->argv[0] );
1855                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1856                                 c->log, c->cr_msg, 0 );
1857                         return(1);
1858                 }
1859         }
1860         return(0);
1861 }
1862
1863 static int
1864 config_schema_dn(ConfigArgs *c) {
1865         if ( c->op == SLAP_CONFIG_EMIT ) {
1866                 int rc = 1;
1867                 if ( !BER_BVISEMPTY( &c->be->be_schemadn )) {
1868                         value_add_one(&c->rvalue_vals, &c->be->be_schemadn);
1869                         value_add_one(&c->rvalue_nvals, &c->be->be_schemandn);
1870                         rc = 0;
1871                 }
1872                 return rc;
1873         } else if ( c->op == LDAP_MOD_DELETE ) {
1874                 ch_free( c->be->be_schemadn.bv_val );
1875                 ch_free( c->be->be_schemandn.bv_val );
1876                 BER_BVZERO( &c->be->be_schemadn );
1877                 BER_BVZERO( &c->be->be_schemandn );
1878                 return 0;
1879         }
1880         ch_free( c->be->be_schemadn.bv_val );
1881         ch_free( c->be->be_schemandn.bv_val );
1882         c->be->be_schemadn = c->value_dn;
1883         c->be->be_schemandn = c->value_ndn;
1884         return(0);
1885 }
1886
1887 static int
1888 config_sizelimit(ConfigArgs *c) {
1889         int i, rc = 0;
1890         struct slap_limits_set *lim = &c->be->be_def_limit;
1891         if (c->op == SLAP_CONFIG_EMIT) {
1892                 char buf[8192];
1893                 struct berval bv;
1894                 bv.bv_val = buf;
1895                 bv.bv_len = 0;
1896                 limits_unparse_one( lim, SLAP_LIMIT_SIZE, &bv, sizeof( buf ) );
1897                 if ( !BER_BVISEMPTY( &bv ))
1898                         value_add_one( &c->rvalue_vals, &bv );
1899                 else
1900                         rc = 1;
1901                 return rc;
1902         } else if ( c->op == LDAP_MOD_DELETE ) {
1903                 /* Reset to defaults */
1904                 lim->lms_s_soft = SLAPD_DEFAULT_SIZELIMIT;
1905                 lim->lms_s_hard = 0;
1906                 lim->lms_s_unchecked = -1;
1907                 lim->lms_s_pr = 0;
1908                 lim->lms_s_pr_hide = 0;
1909                 lim->lms_s_pr_total = 0;
1910                 return 0;
1911         }
1912         for(i = 1; i < c->argc; i++) {
1913                 if(!strncasecmp(c->argv[i], "size", 4)) {
1914                         rc = limits_parse_one(c->argv[i], lim);
1915                         if ( rc ) {
1916                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1917                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1918                                         c->log, c->cr_msg, c->argv[i]);
1919                                 return(1);
1920                         }
1921                 } else {
1922                         if(!strcasecmp(c->argv[i], "unlimited")) {
1923                                 lim->lms_s_soft = -1;
1924                         } else {
1925                                 if ( lutil_atoix( &lim->lms_s_soft, c->argv[i], 0 ) != 0 ) {
1926                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1927                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1928                                                 c->log, c->cr_msg, c->argv[i]);
1929                                         return(1);
1930                                 }
1931                         }
1932                         lim->lms_s_hard = 0;
1933                 }
1934         }
1935         return(0);
1936 }
1937
1938 static int
1939 config_timelimit(ConfigArgs *c) {
1940         int i, rc = 0;
1941         struct slap_limits_set *lim = &c->be->be_def_limit;
1942         if (c->op == SLAP_CONFIG_EMIT) {
1943                 char buf[8192];
1944                 struct berval bv;
1945                 bv.bv_val = buf;
1946                 bv.bv_len = 0;
1947                 limits_unparse_one( lim, SLAP_LIMIT_TIME, &bv, sizeof( buf ) );
1948                 if ( !BER_BVISEMPTY( &bv ))
1949                         value_add_one( &c->rvalue_vals, &bv );
1950                 else
1951                         rc = 1;
1952                 return rc;
1953         } else if ( c->op == LDAP_MOD_DELETE ) {
1954                 /* Reset to defaults */
1955                 lim->lms_t_soft = SLAPD_DEFAULT_TIMELIMIT;
1956                 lim->lms_t_hard = 0;
1957                 return 0;
1958         }
1959         for(i = 1; i < c->argc; i++) {
1960                 if(!strncasecmp(c->argv[i], "time", 4)) {
1961                         rc = limits_parse_one(c->argv[i], lim);
1962                         if ( rc ) {
1963                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1964                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1965                                         c->log, c->cr_msg, c->argv[i]);
1966                                 return(1);
1967                         }
1968                 } else {
1969                         if(!strcasecmp(c->argv[i], "unlimited")) {
1970                                 lim->lms_t_soft = -1;
1971                         } else {
1972                                 if ( lutil_atoix( &lim->lms_t_soft, c->argv[i], 0 ) != 0 ) {
1973                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1974                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1975                                                 c->log, c->cr_msg, c->argv[i]);
1976                                         return(1);
1977                                 }
1978                         }
1979                         lim->lms_t_hard = 0;
1980                 }
1981         }
1982         return(0);
1983 }
1984
1985 static int
1986 config_overlay(ConfigArgs *c) {
1987         if (c->op == SLAP_CONFIG_EMIT) {
1988                 return 1;
1989         } else if ( c->op == LDAP_MOD_DELETE ) {
1990                 assert(0);
1991         }
1992         if(c->argv[1][0] == '-' && overlay_config(c->be, &c->argv[1][1],
1993                 c->valx, &c->bi)) {
1994                 /* log error */
1995                 Debug( LDAP_DEBUG_ANY,
1996                         "%s: (optional) %s overlay \"%s\" configuration failed.\n",
1997                         c->log, c->be == frontendDB ? "global " : "", &c->argv[1][1]);
1998                 return 1;
1999         } else if(overlay_config(c->be, c->argv[1], c->valx, &c->bi)) {
2000                 return(1);
2001         }
2002         return(0);
2003 }
2004
2005 static int
2006 config_subordinate(ConfigArgs *c)
2007 {
2008         int rc = 1;
2009         int advertise;
2010
2011         switch( c->op ) {
2012         case SLAP_CONFIG_EMIT:
2013                 if ( SLAP_GLUE_SUBORDINATE( c->be )) {
2014                         struct berval bv;
2015
2016                         bv.bv_val = SLAP_GLUE_ADVERTISE( c->be ) ? "advertise" : "TRUE";
2017                         bv.bv_len = SLAP_GLUE_ADVERTISE( c->be ) ? STRLENOF("advertise") :
2018                                 STRLENOF("TRUE");
2019
2020                         value_add_one( &c->rvalue_vals, &bv );
2021                         rc = 0;
2022                 }
2023                 break;
2024         case LDAP_MOD_DELETE:
2025                 if ( !c->line  || strcasecmp( c->line, "advertise" )) {
2026                         glue_sub_del( c->be );
2027                 } else {
2028                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_GLUE_ADVERTISE;
2029                 }
2030                 rc = 0;
2031                 break;
2032         case LDAP_MOD_ADD:
2033         case SLAP_CONFIG_ADD:
2034                 advertise = ( c->argc == 2 && !strcasecmp( c->argv[1], "advertise" ));
2035                 rc = glue_sub_add( c->be, advertise, CONFIG_ONLINE_ADD( c ));
2036                 break;
2037         }
2038         return rc;
2039 }
2040
2041 static int
2042 config_suffix(ConfigArgs *c)
2043 {
2044         Backend *tbe;
2045         struct berval pdn, ndn;
2046         char    *notallowed = NULL;
2047
2048         if ( c->be == frontendDB ) {
2049                 notallowed = "frontend";
2050
2051         } else if ( SLAP_MONITOR(c->be) ) {
2052                 notallowed = "monitor";
2053
2054         } else if ( SLAP_CONFIG(c->be) ) {
2055                 notallowed = "config";
2056         }
2057
2058         if ( notallowed != NULL ) {
2059                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
2060
2061                 switch ( c->op ) {
2062                 case LDAP_MOD_ADD:
2063                 case LDAP_MOD_DELETE:
2064                 case LDAP_MOD_REPLACE:
2065                 case LDAP_MOD_INCREMENT:
2066                 case SLAP_CONFIG_ADD:
2067                         if ( !BER_BVISNULL( &c->value_dn ) ) {
2068                                 snprintf( buf, sizeof( buf ), "<%s> ",
2069                                                 c->value_dn.bv_val );
2070                         }
2071
2072                         Debug(LDAP_DEBUG_ANY,
2073                                 "%s: suffix %snot allowed in %s database.\n",
2074                                 c->log, buf, notallowed );
2075                         break;
2076
2077                 case SLAP_CONFIG_EMIT:
2078                         /* don't complain when emitting... */
2079                         break;
2080
2081                 default:
2082                         /* FIXME: don't know what values may be valid;
2083                          * please remove assertion, or add legal values
2084                          * to either block */
2085                         assert( 0 );
2086                         break;
2087                 }
2088
2089                 return 1;
2090         }
2091
2092         if (c->op == SLAP_CONFIG_EMIT) {
2093                 if ( c->be->be_suffix == NULL
2094                                 || BER_BVISNULL( &c->be->be_suffix[0] ) )
2095                 {
2096                         return 1;
2097                 } else {
2098                         value_add( &c->rvalue_vals, c->be->be_suffix );
2099                         value_add( &c->rvalue_nvals, c->be->be_nsuffix );
2100                         return 0;
2101                 }
2102         } else if ( c->op == LDAP_MOD_DELETE ) {
2103                 if ( c->valx < 0 ) {
2104                         ber_bvarray_free( c->be->be_suffix );
2105                         ber_bvarray_free( c->be->be_nsuffix );
2106                         c->be->be_suffix = NULL;
2107                         c->be->be_nsuffix = NULL;
2108                 } else {
2109                         int i = c->valx;
2110                         ch_free( c->be->be_suffix[i].bv_val );
2111                         ch_free( c->be->be_nsuffix[i].bv_val );
2112                         do {
2113                                 c->be->be_suffix[i] = c->be->be_suffix[i+1];
2114                                 c->be->be_nsuffix[i] = c->be->be_nsuffix[i+1];
2115                                 i++;
2116                         } while ( !BER_BVISNULL( &c->be->be_suffix[i] ) );
2117                 }
2118                 return 0;
2119         }
2120
2121 #ifdef SLAPD_MONITOR_DN
2122         if(!strcasecmp(c->argv[1], SLAPD_MONITOR_DN)) {
2123                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> DN is reserved for monitoring slapd",
2124                         c->argv[0] );
2125                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2126                         c->log, c->cr_msg, SLAPD_MONITOR_DN);
2127                 return(1);
2128         }
2129 #endif
2130
2131         pdn = c->value_dn;
2132         ndn = c->value_ndn;
2133         if (SLAP_DBHIDDEN( c->be ))
2134                 tbe = NULL;
2135         else
2136                 tbe = select_backend(&ndn, 0);
2137         if(tbe == c->be) {
2138                 Debug( LDAP_DEBUG_ANY, "%s: suffix already served by this backend!.\n",
2139                         c->log, 0, 0);
2140                 return 1;
2141                 free(pdn.bv_val);
2142                 free(ndn.bv_val);
2143         } else if(tbe) {
2144                 BackendDB *b2 = tbe;
2145
2146                 /* Does tbe precede be? */
2147                 while (( b2 = LDAP_STAILQ_NEXT(b2, be_next )) && b2 && b2 != c->be );
2148
2149                 if ( b2 ) {
2150                         char    *type = tbe->bd_info->bi_type;
2151
2152                         if ( overlay_is_over( tbe ) ) {
2153                                 slap_overinfo   *oi = (slap_overinfo *)tbe->bd_info->bi_private;
2154                                 type = oi->oi_orig->bi_type;
2155                         }
2156
2157                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> namingContext \"%s\" "
2158                                 "already served by a preceding %s database",
2159                                 c->argv[0], pdn.bv_val, type );
2160                         Debug(LDAP_DEBUG_ANY, "%s: %s serving namingContext \"%s\"\n",
2161                                 c->log, c->cr_msg, tbe->be_suffix[0].bv_val);
2162                         free(pdn.bv_val);
2163                         free(ndn.bv_val);
2164                         return(1);
2165                 }
2166         }
2167         if(pdn.bv_len == 0 && default_search_nbase.bv_len) {
2168                 Debug(LDAP_DEBUG_ANY, "%s: suffix DN empty and default search "
2169                         "base provided \"%s\" (assuming okay)\n",
2170                         c->log, default_search_base.bv_val, 0);
2171         }
2172         ber_bvarray_add(&c->be->be_suffix, &pdn);
2173         ber_bvarray_add(&c->be->be_nsuffix, &ndn);
2174         return(0);
2175 }
2176
2177 static int
2178 config_rootdn(ConfigArgs *c) {
2179         if (c->op == SLAP_CONFIG_EMIT) {
2180                 if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2181                         value_add_one(&c->rvalue_vals, &c->be->be_rootdn);
2182                         value_add_one(&c->rvalue_nvals, &c->be->be_rootndn);
2183                         return 0;
2184                 } else {
2185                         return 1;
2186                 }
2187         } else if ( c->op == LDAP_MOD_DELETE ) {
2188                 ch_free( c->be->be_rootdn.bv_val );
2189                 ch_free( c->be->be_rootndn.bv_val );
2190                 BER_BVZERO( &c->be->be_rootdn );
2191                 BER_BVZERO( &c->be->be_rootndn );
2192                 return 0;
2193         }
2194         if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2195                 ch_free( c->be->be_rootdn.bv_val );
2196                 ch_free( c->be->be_rootndn.bv_val );
2197         }
2198         c->be->be_rootdn = c->value_dn;
2199         c->be->be_rootndn = c->value_ndn;
2200         return(0);
2201 }
2202
2203 static int
2204 config_rootpw(ConfigArgs *c) {
2205         Backend *tbe;
2206
2207         if (c->op == SLAP_CONFIG_EMIT) {
2208                 if (!BER_BVISEMPTY(&c->be->be_rootpw)) {
2209                         /* don't copy, because "rootpw" is marked
2210                          * as CFG_BERVAL */
2211                         c->value_bv = c->be->be_rootpw;
2212                         return 0;
2213                 }
2214                 return 1;
2215         } else if ( c->op == LDAP_MOD_DELETE ) {
2216                 ch_free( c->be->be_rootpw.bv_val );
2217                 BER_BVZERO( &c->be->be_rootpw );
2218                 return 0;
2219         }
2220
2221         tbe = select_backend(&c->be->be_rootndn, 0);
2222         if(tbe != c->be) {
2223                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> can only be set when rootdn is under suffix",
2224                         c->argv[0] );
2225                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2226                         c->log, c->cr_msg, 0);
2227                 return(1);
2228         }
2229         if ( !BER_BVISNULL( &c->be->be_rootpw ))
2230                 ch_free( c->be->be_rootpw.bv_val );
2231         c->be->be_rootpw = c->value_bv;
2232         return(0);
2233 }
2234
2235 static int
2236 config_restrict(ConfigArgs *c) {
2237         slap_mask_t restrictops = 0;
2238         int i;
2239         slap_verbmasks restrictable_ops[] = {
2240                 { BER_BVC("bind"),              SLAP_RESTRICT_OP_BIND },
2241                 { BER_BVC("add"),               SLAP_RESTRICT_OP_ADD },
2242                 { BER_BVC("modify"),            SLAP_RESTRICT_OP_MODIFY },
2243                 { BER_BVC("rename"),            SLAP_RESTRICT_OP_RENAME },
2244                 { BER_BVC("modrdn"),            0 },
2245                 { BER_BVC("delete"),            SLAP_RESTRICT_OP_DELETE },
2246                 { BER_BVC("search"),            SLAP_RESTRICT_OP_SEARCH },
2247                 { BER_BVC("compare"),           SLAP_RESTRICT_OP_COMPARE },
2248                 { BER_BVC("read"),              SLAP_RESTRICT_OP_READS },
2249                 { BER_BVC("write"),             SLAP_RESTRICT_OP_WRITES },
2250                 { BER_BVC("extended"),          SLAP_RESTRICT_OP_EXTENDED },
2251                 { BER_BVC("extended=" LDAP_EXOP_START_TLS ),            SLAP_RESTRICT_EXOP_START_TLS },
2252                 { BER_BVC("extended=" LDAP_EXOP_MODIFY_PASSWD ),        SLAP_RESTRICT_EXOP_MODIFY_PASSWD },
2253                 { BER_BVC("extended=" LDAP_EXOP_X_WHO_AM_I ),           SLAP_RESTRICT_EXOP_WHOAMI },
2254                 { BER_BVC("extended=" LDAP_EXOP_X_CANCEL ),             SLAP_RESTRICT_EXOP_CANCEL },
2255                 { BER_BVC("all"),               SLAP_RESTRICT_OP_ALL },
2256                 { BER_BVNULL,   0 }
2257         };
2258
2259         if (c->op == SLAP_CONFIG_EMIT) {
2260                 return mask_to_verbs( restrictable_ops, c->be->be_restrictops,
2261                         &c->rvalue_vals );
2262         } else if ( c->op == LDAP_MOD_DELETE ) {
2263                 if ( !c->line ) {
2264                         c->be->be_restrictops = 0;
2265                 } else {
2266                         restrictops = verb_to_mask( c->line, restrictable_ops );
2267                         c->be->be_restrictops ^= restrictops;
2268                 }
2269                 return 0;
2270         }
2271         i = verbs_to_mask( c->argc, c->argv, restrictable_ops, &restrictops );
2272         if ( i ) {
2273                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown operation", c->argv[0] );
2274                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2275                         c->log, c->cr_msg, c->argv[i]);
2276                 return(1);
2277         }
2278         if ( restrictops & SLAP_RESTRICT_OP_EXTENDED )
2279                 restrictops &= ~SLAP_RESTRICT_EXOP_MASK;
2280         c->be->be_restrictops |= restrictops;
2281         return(0);
2282 }
2283
2284 static int
2285 config_allows(ConfigArgs *c) {
2286         slap_mask_t allows = 0;
2287         int i;
2288         slap_verbmasks allowable_ops[] = {
2289                 { BER_BVC("bind_v2"),           SLAP_ALLOW_BIND_V2 },
2290                 { BER_BVC("bind_anon_cred"),    SLAP_ALLOW_BIND_ANON_CRED },
2291                 { BER_BVC("bind_anon_dn"),      SLAP_ALLOW_BIND_ANON_DN },
2292                 { BER_BVC("update_anon"),       SLAP_ALLOW_UPDATE_ANON },
2293                 { BER_BVC("proxy_authz_anon"),  SLAP_ALLOW_PROXY_AUTHZ_ANON },
2294                 { BER_BVNULL,   0 }
2295         };
2296         if (c->op == SLAP_CONFIG_EMIT) {
2297                 return mask_to_verbs( allowable_ops, global_allows, &c->rvalue_vals );
2298         } else if ( c->op == LDAP_MOD_DELETE ) {
2299                 if ( !c->line ) {
2300                         global_allows = 0;
2301                 } else {
2302                         allows = verb_to_mask( c->line, allowable_ops );
2303                         global_allows ^= allows;
2304                 }
2305                 return 0;
2306         }
2307         i = verbs_to_mask(c->argc, c->argv, allowable_ops, &allows);
2308         if ( i ) {
2309                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2310                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2311                         c->log, c->cr_msg, c->argv[i]);
2312                 return(1);
2313         }
2314         global_allows |= allows;
2315         return(0);
2316 }
2317
2318 static int
2319 config_disallows(ConfigArgs *c) {
2320         slap_mask_t disallows = 0;
2321         int i;
2322         slap_verbmasks disallowable_ops[] = {
2323                 { BER_BVC("bind_anon"),         SLAP_DISALLOW_BIND_ANON },
2324                 { BER_BVC("bind_simple"),       SLAP_DISALLOW_BIND_SIMPLE },
2325                 { BER_BVC("tls_2_anon"),                SLAP_DISALLOW_TLS_2_ANON },
2326                 { BER_BVC("tls_authc"),         SLAP_DISALLOW_TLS_AUTHC },
2327                 { BER_BVNULL, 0 }
2328         };
2329         if (c->op == SLAP_CONFIG_EMIT) {
2330                 return mask_to_verbs( disallowable_ops, global_disallows, &c->rvalue_vals );
2331         } else if ( c->op == LDAP_MOD_DELETE ) {
2332                 if ( !c->line ) {
2333                         global_disallows = 0;
2334                 } else {
2335                         disallows = verb_to_mask( c->line, disallowable_ops );
2336                         global_disallows ^= disallows;
2337                 }
2338                 return 0;
2339         }
2340         i = verbs_to_mask(c->argc, c->argv, disallowable_ops, &disallows);
2341         if ( i ) {
2342                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2343                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2344                         c->log, c->cr_msg, c->argv[i]);
2345                 return(1);
2346         }
2347         global_disallows |= disallows;
2348         return(0);
2349 }
2350
2351 static int
2352 config_requires(ConfigArgs *c) {
2353         slap_mask_t requires = frontendDB->be_requires;
2354         int i, argc = c->argc;
2355         char **argv = c->argv;
2356
2357         slap_verbmasks requires_ops[] = {
2358                 { BER_BVC("bind"),              SLAP_REQUIRE_BIND },
2359                 { BER_BVC("LDAPv3"),            SLAP_REQUIRE_LDAP_V3 },
2360                 { BER_BVC("authc"),             SLAP_REQUIRE_AUTHC },
2361                 { BER_BVC("sasl"),              SLAP_REQUIRE_SASL },
2362                 { BER_BVC("strong"),            SLAP_REQUIRE_STRONG },
2363                 { BER_BVNULL, 0 }
2364         };
2365         if (c->op == SLAP_CONFIG_EMIT) {
2366                 return mask_to_verbs( requires_ops, c->be->be_requires, &c->rvalue_vals );
2367         } else if ( c->op == LDAP_MOD_DELETE ) {
2368                 if ( !c->line ) {
2369                         c->be->be_requires = 0;
2370                 } else {
2371                         requires = verb_to_mask( c->line, requires_ops );
2372                         c->be->be_requires ^= requires;
2373                 }
2374                 return 0;
2375         }
2376         /* "none" can only be first, to wipe out default/global values */
2377         if ( strcasecmp( c->argv[ 1 ], "none" ) == 0 ) {
2378                 argv++;
2379                 argc--;
2380                 requires = 0;
2381         }
2382         i = verbs_to_mask(argc, argv, requires_ops, &requires);
2383         if ( i ) {
2384                 if (strcasecmp( c->argv[ i ], "none" ) == 0 ) {
2385                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> \"none\" (#%d) must be listed first", c->argv[0], i - 1 );
2386                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2387                                 c->log, c->cr_msg, 0);
2388                 } else {
2389                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature #%d", c->argv[0], i - 1 );
2390                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2391                                 c->log, c->cr_msg, c->argv[i]);
2392                 }
2393                 return(1);
2394         }
2395         c->be->be_requires = requires;
2396         return(0);
2397 }
2398
2399 static slap_verbmasks   *loglevel_ops;
2400
2401 static int
2402 loglevel_init( void )
2403 {
2404         slap_verbmasks  lo[] = {
2405                 { BER_BVC("Any"),       -1 },
2406                 { BER_BVC("Trace"),     LDAP_DEBUG_TRACE },
2407                 { BER_BVC("Packets"),   LDAP_DEBUG_PACKETS },
2408                 { BER_BVC("Args"),      LDAP_DEBUG_ARGS },
2409                 { BER_BVC("Conns"),     LDAP_DEBUG_CONNS },
2410                 { BER_BVC("BER"),       LDAP_DEBUG_BER },
2411                 { BER_BVC("Filter"),    LDAP_DEBUG_FILTER },
2412                 { BER_BVC("Config"),    LDAP_DEBUG_CONFIG },
2413                 { BER_BVC("ACL"),       LDAP_DEBUG_ACL },
2414                 { BER_BVC("Stats"),     LDAP_DEBUG_STATS },
2415                 { BER_BVC("Stats2"),    LDAP_DEBUG_STATS2 },
2416                 { BER_BVC("Shell"),     LDAP_DEBUG_SHELL },
2417                 { BER_BVC("Parse"),     LDAP_DEBUG_PARSE },
2418 #if 0   /* no longer used (nor supported) */
2419                 { BER_BVC("Cache"),     LDAP_DEBUG_CACHE },
2420                 { BER_BVC("Index"),     LDAP_DEBUG_INDEX },
2421 #endif
2422                 { BER_BVC("Sync"),      LDAP_DEBUG_SYNC },
2423                 { BER_BVC("None"),      LDAP_DEBUG_NONE },
2424                 { BER_BVNULL,           0 }
2425         };
2426
2427         return slap_verbmasks_init( &loglevel_ops, lo );
2428 }
2429
2430 static void
2431 loglevel_destroy( void )
2432 {
2433         if ( loglevel_ops ) {
2434                 (void)slap_verbmasks_destroy( loglevel_ops );
2435         }
2436         loglevel_ops = NULL;
2437 }
2438
2439 static slap_mask_t      loglevel_ignore[] = { -1, 0 };
2440
2441 int
2442 slap_loglevel_register( slap_mask_t m, struct berval *s )
2443 {
2444         int     rc;
2445
2446         if ( loglevel_ops == NULL ) {
2447                 loglevel_init();
2448         }
2449
2450         rc = slap_verbmasks_append( &loglevel_ops, m, s, loglevel_ignore );
2451
2452         if ( rc != 0 ) {
2453                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_register(%lu, \"%s\") failed\n",
2454                         m, s->bv_val, 0 );
2455         }
2456
2457         return rc;
2458 }
2459
2460 int
2461 slap_loglevel_get( struct berval *s, int *l )
2462 {
2463         int             rc;
2464         slap_mask_t     m, i;
2465
2466         if ( loglevel_ops == NULL ) {
2467                 loglevel_init();
2468         }
2469
2470         for ( m = 0, i = 1; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2471                 m |= loglevel_ops[ i ].mask;
2472         }
2473
2474         for ( i = 1; m & i; i <<= 1 )
2475                 ;
2476
2477         if ( i == 0 ) {
2478                 return -1;
2479         }
2480
2481         rc = slap_verbmasks_append( &loglevel_ops, i, s, loglevel_ignore );
2482
2483         if ( rc != 0 ) {
2484                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_get(%lu, \"%s\") failed\n",
2485                         i, s->bv_val, 0 );
2486
2487         } else {
2488                 *l = i;
2489         }
2490
2491         return rc;
2492 }
2493
2494 int
2495 str2loglevel( const char *s, int *l )
2496 {
2497         int     i;
2498
2499         if ( loglevel_ops == NULL ) {
2500                 loglevel_init();
2501         }
2502
2503         i = verb_to_mask( s, loglevel_ops );
2504
2505         if ( BER_BVISNULL( &loglevel_ops[ i ].word ) ) {
2506                 return -1;
2507         }
2508
2509         *l = loglevel_ops[ i ].mask;
2510
2511         return 0;
2512 }
2513
2514 const char *
2515 loglevel2str( int l )
2516 {
2517         struct berval   bv = BER_BVNULL;
2518
2519         loglevel2bv( l, &bv );
2520
2521         return bv.bv_val;
2522 }
2523
2524 int
2525 loglevel2bv( int l, struct berval *bv )
2526 {
2527         if ( loglevel_ops == NULL ) {
2528                 loglevel_init();
2529         }
2530
2531         BER_BVZERO( bv );
2532
2533         return enum_to_verb( loglevel_ops, l, bv ) == -1;
2534 }
2535
2536 int
2537 loglevel2bvarray( int l, BerVarray *bva )
2538 {
2539         if ( loglevel_ops == NULL ) {
2540                 loglevel_init();
2541         }
2542
2543         return mask_to_verbs( loglevel_ops, l, bva );
2544 }
2545
2546 int
2547 loglevel_print( FILE *out )
2548 {
2549         int     i;
2550
2551         if ( loglevel_ops == NULL ) {
2552                 loglevel_init();
2553         }
2554
2555         fprintf( out, "Installed log subsystems:\n\n" );
2556         for ( i = 0; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2557                 fprintf( out, "\t%-30s (%lu)\n",
2558                         loglevel_ops[ i ].word.bv_val,
2559                         loglevel_ops[ i ].mask );
2560         }
2561
2562         fprintf( out, "\nNOTE: custom log subsystems may be later installed "
2563                 "by specific code\n\n" );
2564
2565         return 0;
2566 }
2567
2568 static int config_syslog;
2569
2570 static int
2571 config_loglevel(ConfigArgs *c) {
2572         int i;
2573
2574         if ( loglevel_ops == NULL ) {
2575                 loglevel_init();
2576         }
2577
2578         if (c->op == SLAP_CONFIG_EMIT) {
2579                 /* Get default or commandline slapd setting */
2580                 if ( ldap_syslog && !config_syslog )
2581                         config_syslog = ldap_syslog;
2582                 return loglevel2bvarray( config_syslog, &c->rvalue_vals );
2583
2584         } else if ( c->op == LDAP_MOD_DELETE ) {
2585                 if ( !c->line ) {
2586                         config_syslog = 0;
2587                 } else {
2588                         int level = verb_to_mask( c->line, loglevel_ops );
2589                         config_syslog ^= level;
2590                 }
2591                 if ( slapMode & SLAP_SERVER_MODE ) {
2592                         ldap_syslog = config_syslog;
2593                 }
2594                 return 0;
2595         }
2596
2597         for( i=1; i < c->argc; i++ ) {
2598                 int     level;
2599
2600                 if ( isdigit((unsigned char)c->argv[i][0]) || c->argv[i][0] == '-' ) {
2601                         if( lutil_atoi( &level, c->argv[i] ) != 0 ) {
2602                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse 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                 } else {
2608                         if ( str2loglevel( c->argv[i], &level ) ) {
2609                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown level", c->argv[0] );
2610                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2611                                         c->log, c->cr_msg, c->argv[i]);
2612                                 return( 1 );
2613                         }
2614                 }
2615                 /* Explicitly setting a zero clears all the levels */
2616                 if ( level )
2617                         config_syslog |= level;
2618                 else
2619                         config_syslog = 0;
2620         }
2621         if ( slapMode & SLAP_SERVER_MODE ) {
2622                 ldap_syslog = config_syslog;
2623         }
2624         return(0);
2625 }
2626
2627 static int
2628 config_referral(ConfigArgs *c) {
2629         struct berval val;
2630         if (c->op == SLAP_CONFIG_EMIT) {
2631                 if ( default_referral ) {
2632                         value_add( &c->rvalue_vals, default_referral );
2633                         return 0;
2634                 } else {
2635                         return 1;
2636                 }
2637         } else if ( c->op == LDAP_MOD_DELETE ) {
2638                 if ( c->valx < 0 ) {
2639                         ber_bvarray_free( default_referral );
2640                         default_referral = NULL;
2641                 } else {
2642                         int i = c->valx;
2643                         ch_free( default_referral[i].bv_val );
2644                         for (; default_referral[i].bv_val; i++ )
2645                                 default_referral[i] = default_referral[i+1];
2646                 }
2647                 return 0;
2648         }
2649         if(validate_global_referral(c->argv[1])) {
2650                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2651                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2652                         c->log, c->cr_msg, c->argv[1]);
2653                 return(1);
2654         }
2655
2656         ber_str2bv(c->argv[1], 0, 0, &val);
2657         if(value_add_one(&default_referral, &val)) return(LDAP_OTHER);
2658         return(0);
2659 }
2660
2661 static struct {
2662         struct berval key;
2663         int off;
2664 } sec_keys[] = {
2665         { BER_BVC("ssf="), offsetof(slap_ssf_set_t, sss_ssf) },
2666         { BER_BVC("transport="), offsetof(slap_ssf_set_t, sss_transport) },
2667         { BER_BVC("tls="), offsetof(slap_ssf_set_t, sss_tls) },
2668         { BER_BVC("sasl="), offsetof(slap_ssf_set_t, sss_sasl) },
2669         { BER_BVC("update_ssf="), offsetof(slap_ssf_set_t, sss_update_ssf) },
2670         { BER_BVC("update_transport="), offsetof(slap_ssf_set_t, sss_update_transport) },
2671         { BER_BVC("update_tls="), offsetof(slap_ssf_set_t, sss_update_tls) },
2672         { BER_BVC("update_sasl="), offsetof(slap_ssf_set_t, sss_update_sasl) },
2673         { BER_BVC("simple_bind="), offsetof(slap_ssf_set_t, sss_simple_bind) },
2674         { BER_BVNULL, 0 }
2675 };
2676
2677 static int
2678 config_security(ConfigArgs *c) {
2679         slap_ssf_set_t *set = &c->be->be_ssf_set;
2680         char *next;
2681         int i, j;
2682         if (c->op == SLAP_CONFIG_EMIT) {
2683                 char numbuf[32];
2684                 struct berval bv;
2685                 slap_ssf_t *tgt;
2686                 int rc = 1;
2687
2688                 for (i=0; !BER_BVISNULL( &sec_keys[i].key ); i++) {
2689                         tgt = (slap_ssf_t *)((char *)set + sec_keys[i].off);
2690                         if ( *tgt ) {
2691                                 rc = 0;
2692                                 bv.bv_len = snprintf( numbuf, sizeof( numbuf ), "%u", *tgt );
2693                                 if ( bv.bv_len >= sizeof( numbuf ) ) {
2694                                         ber_bvarray_free_x( c->rvalue_vals, NULL );
2695                                         c->rvalue_vals = NULL;
2696                                         rc = 1;
2697                                         break;
2698                                 }
2699                                 bv.bv_len += sec_keys[i].key.bv_len;
2700                                 bv.bv_val = ch_malloc( bv.bv_len + 1);
2701                                 next = lutil_strcopy( bv.bv_val, sec_keys[i].key.bv_val );
2702                                 strcpy( next, numbuf );
2703                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2704                         }
2705                 }
2706                 return rc;
2707         }
2708         for(i = 1; i < c->argc; i++) {
2709                 slap_ssf_t *tgt = NULL;
2710                 char *src = NULL;
2711                 for ( j=0; !BER_BVISNULL( &sec_keys[j].key ); j++ ) {
2712                         if(!strncasecmp(c->argv[i], sec_keys[j].key.bv_val,
2713                                 sec_keys[j].key.bv_len)) {
2714                                 src = c->argv[i] + sec_keys[j].key.bv_len;
2715                                 tgt = (slap_ssf_t *)((char *)set + sec_keys[j].off);
2716                                 break;
2717                         }
2718                 }
2719                 if ( !tgt ) {
2720                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown 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                 if ( lutil_atou( tgt, src ) != 0 ) {
2727                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse factor", c->argv[0] );
2728                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2729                                 c->log, c->cr_msg, c->argv[i]);
2730                         return(1);
2731                 }
2732         }
2733         return(0);
2734 }
2735
2736 char *
2737 anlist_unparse( AttributeName *an, char *ptr, ber_len_t buflen ) {
2738         int comma = 0;
2739         char *start = ptr;
2740
2741         for (; !BER_BVISNULL( &an->an_name ); an++) {
2742                 /* if buflen == 0, assume the buffer size has been 
2743                  * already checked otherwise */
2744                 if ( buflen > 0 && buflen - ( ptr - start ) < comma + an->an_name.bv_len ) return NULL;
2745                 if ( comma ) *ptr++ = ',';
2746                 ptr = lutil_strcopy( ptr, an->an_name.bv_val );
2747                 comma = 1;
2748         }
2749         return ptr;
2750 }
2751
2752 static int
2753 config_updatedn(ConfigArgs *c) {
2754         if (c->op == SLAP_CONFIG_EMIT) {
2755                 if (!BER_BVISEMPTY(&c->be->be_update_ndn)) {
2756                         value_add_one(&c->rvalue_vals, &c->be->be_update_ndn);
2757                         value_add_one(&c->rvalue_nvals, &c->be->be_update_ndn);
2758                         return 0;
2759                 }
2760                 return 1;
2761         } else if ( c->op == LDAP_MOD_DELETE ) {
2762                 ch_free( c->be->be_update_ndn.bv_val );
2763                 BER_BVZERO( &c->be->be_update_ndn );
2764                 SLAP_DBFLAGS(c->be) ^= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SLURP_SHADOW);
2765                 return 0;
2766         }
2767         if(SLAP_SHADOW(c->be)) {
2768                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database already shadowed", c->argv[0] );
2769                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2770                         c->log, c->cr_msg, 0);
2771                 return(1);
2772         }
2773
2774         ber_memfree_x( c->value_dn.bv_val, NULL );
2775         if ( !BER_BVISNULL( &c->be->be_update_ndn ) ) {
2776                 ber_memfree_x( c->be->be_update_ndn.bv_val, NULL );
2777         }
2778         c->be->be_update_ndn = c->value_ndn;
2779         BER_BVZERO( &c->value_dn );
2780         BER_BVZERO( &c->value_ndn );
2781
2782         return config_slurp_shadow( c );
2783 }
2784
2785 int
2786 config_shadow( ConfigArgs *c, int flag )
2787 {
2788         char    *notallowed = NULL;
2789
2790         if ( c->be == frontendDB ) {
2791                 notallowed = "frontend";
2792
2793         } else if ( SLAP_MONITOR(c->be) ) {
2794                 notallowed = "monitor";
2795         }
2796
2797         if ( notallowed != NULL ) {
2798                 Debug( LDAP_DEBUG_ANY, "%s: %s database cannot be shadow.\n", c->log, notallowed, 0 );
2799                 return 1;
2800         }
2801
2802         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SINGLE_SHADOW | flag);
2803
2804         return 0;
2805 }
2806
2807 static int
2808 config_updateref(ConfigArgs *c) {
2809         struct berval val;
2810         if (c->op == SLAP_CONFIG_EMIT) {
2811                 if ( c->be->be_update_refs ) {
2812                         value_add( &c->rvalue_vals, c->be->be_update_refs );
2813                         return 0;
2814                 } else {
2815                         return 1;
2816                 }
2817         } else if ( c->op == LDAP_MOD_DELETE ) {
2818                 if ( c->valx < 0 ) {
2819                         ber_bvarray_free( c->be->be_update_refs );
2820                         c->be->be_update_refs = NULL;
2821                 } else {
2822                         int i = c->valx;
2823                         ch_free( c->be->be_update_refs[i].bv_val );
2824                         for (; c->be->be_update_refs[i].bv_val; i++)
2825                                 c->be->be_update_refs[i] = c->be->be_update_refs[i+1];
2826                 }
2827                 return 0;
2828         }
2829         if(!SLAP_SHADOW(c->be) && !c->be->be_syncinfo) {
2830                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> must appear after syncrepl or updatedn",
2831                         c->argv[0] );
2832                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2833                         c->log, c->cr_msg, 0);
2834                 return(1);
2835         }
2836
2837         if(validate_global_referral(c->argv[1])) {
2838                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2839                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2840                         c->log, c->cr_msg, c->argv[1]);
2841                 return(1);
2842         }
2843         ber_str2bv(c->argv[1], 0, 0, &val);
2844         if(value_add_one(&c->be->be_update_refs, &val)) return(LDAP_OTHER);
2845         return(0);
2846 }
2847
2848 static int
2849 config_obsolete(ConfigArgs *c) {
2850         if (c->op == SLAP_CONFIG_EMIT)
2851                 return 1;
2852
2853         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> keyword is obsolete (ignored)",
2854                 c->argv[0] );
2855         Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0);
2856         return(0);
2857 }
2858
2859 static int
2860 config_include(ConfigArgs *c) {
2861         int savelineno = c->lineno;
2862         int rc;
2863         ConfigFile *cf;
2864         ConfigFile *cfsave = cfn;
2865         ConfigFile *cf2 = NULL;
2866
2867         /* No dynamic config for include files */
2868         cf = ch_calloc( 1, sizeof(ConfigFile));
2869         if ( cfn->c_kids ) {
2870                 for (cf2=cfn->c_kids; cf2 && cf2->c_sibs; cf2=cf2->c_sibs) ;
2871                 cf2->c_sibs = cf;
2872         } else {
2873                 cfn->c_kids = cf;
2874         }
2875         cfn = cf;
2876         ber_str2bv( c->argv[1], 0, 1, &cf->c_file );
2877         rc = read_config_file(c->argv[1], c->depth + 1, c, config_back_cf_table);
2878         c->lineno = savelineno - 1;
2879         cfn = cfsave;
2880         if ( rc ) {
2881                 if ( cf2 ) cf2->c_sibs = NULL;
2882                 else cfn->c_kids = NULL;
2883                 ch_free( cf->c_file.bv_val );
2884                 ch_free( cf );
2885         } else {
2886                 c->private = cf;
2887         }
2888         return(rc);
2889 }
2890
2891 #ifdef HAVE_TLS
2892 static int
2893 config_tls_option(ConfigArgs *c) {
2894         int flag;
2895         LDAP *ld = slap_tls_ld;
2896         switch(c->type) {
2897         case CFG_TLS_RAND:      flag = LDAP_OPT_X_TLS_RANDOM_FILE;      ld = NULL; break;
2898         case CFG_TLS_CIPHER:    flag = LDAP_OPT_X_TLS_CIPHER_SUITE;     break;
2899         case CFG_TLS_CERT_FILE: flag = LDAP_OPT_X_TLS_CERTFILE;         break;  
2900         case CFG_TLS_CERT_KEY:  flag = LDAP_OPT_X_TLS_KEYFILE;          break;
2901         case CFG_TLS_CA_PATH:   flag = LDAP_OPT_X_TLS_CACERTDIR;        break;
2902         case CFG_TLS_CA_FILE:   flag = LDAP_OPT_X_TLS_CACERTFILE;       break;
2903         case CFG_TLS_DH_FILE:   flag = LDAP_OPT_X_TLS_DHFILE;   break;
2904 #ifdef HAVE_GNUTLS
2905         case CFG_TLS_CRL_FILE:  flag = LDAP_OPT_X_TLS_CRLFILE;  break;
2906 #endif
2907         default:                Debug(LDAP_DEBUG_ANY, "%s: "
2908                                         "unknown tls_option <0x%x>\n",
2909                                         c->log, c->type, 0);
2910                 return 1;
2911         }
2912         if (c->op == SLAP_CONFIG_EMIT) {
2913                 return ldap_pvt_tls_get_option( ld, flag, &c->value_string );
2914         } else if ( c->op == LDAP_MOD_DELETE ) {
2915                 return ldap_pvt_tls_set_option( ld, flag, NULL );
2916         }
2917         ch_free(c->value_string);
2918         return(ldap_pvt_tls_set_option(ld, flag, c->argv[1]));
2919 }
2920
2921 /* FIXME: this ought to be provided by libldap */
2922 static int
2923 config_tls_config(ConfigArgs *c) {
2924         int i, flag;
2925         switch(c->type) {
2926         case CFG_TLS_CRLCHECK:  flag = LDAP_OPT_X_TLS_CRLCHECK; break;
2927         case CFG_TLS_VERIFY:    flag = LDAP_OPT_X_TLS_REQUIRE_CERT; break;
2928         default:
2929                 Debug(LDAP_DEBUG_ANY, "%s: "
2930                                 "unknown tls_option <0x%x>\n",
2931                                 c->log, c->type, 0);
2932                 return 1;
2933         }
2934         if (c->op == SLAP_CONFIG_EMIT) {
2935                 return slap_tls_get_config( slap_tls_ld, flag, &c->value_string );
2936         } else if ( c->op == LDAP_MOD_DELETE ) {
2937                 int i = 0;
2938                 return ldap_pvt_tls_set_option( slap_tls_ld, flag, &i );
2939         }
2940         ch_free( c->value_string );
2941         if ( isdigit( (unsigned char)c->argv[1][0] ) ) {
2942                 if ( lutil_atoi( &i, c->argv[1] ) != 0 ) {
2943                         Debug(LDAP_DEBUG_ANY, "%s: "
2944                                 "unable to parse %s \"%s\"\n",
2945                                 c->log, c->argv[0], c->argv[1] );
2946                         return 1;
2947                 }
2948                 return(ldap_pvt_tls_set_option(slap_tls_ld, flag, &i));
2949         } else {
2950                 return(ldap_int_tls_config(slap_tls_ld, flag, c->argv[1]));
2951         }
2952 }
2953 #endif
2954
2955 static CfEntryInfo *
2956 config_find_base( CfEntryInfo *root, struct berval *dn, CfEntryInfo **last )
2957 {
2958         struct berval cdn;
2959         char *c;
2960
2961         if ( !root ) {
2962                 *last = NULL;
2963                 return NULL;
2964         }
2965
2966         if ( dn_match( &root->ce_entry->e_nname, dn ))
2967                 return root;
2968
2969         c = dn->bv_val+dn->bv_len;
2970         for (;*c != ',';c--);
2971
2972         while(root) {
2973                 *last = root;
2974                 for (--c;c>dn->bv_val && *c != ',';c--);
2975                 cdn.bv_val = c;
2976                 if ( *c == ',' )
2977                         cdn.bv_val++;
2978                 cdn.bv_len = dn->bv_len - (cdn.bv_val - dn->bv_val);
2979
2980                 root = root->ce_kids;
2981
2982                 for (;root;root=root->ce_sibs) {
2983                         if ( dn_match( &root->ce_entry->e_nname, &cdn )) {
2984                                 if ( cdn.bv_val == dn->bv_val ) {
2985                                         return root;
2986                                 }
2987                                 break;
2988                         }
2989                 }
2990         }
2991         return root;
2992 }
2993
2994 typedef struct setup_cookie {
2995         CfBackInfo *cfb;
2996         ConfigArgs *ca;
2997         Entry *frontend;
2998         Entry *config;
2999         int     got_frontend;
3000         int got_config;
3001 } setup_cookie;
3002
3003 static int
3004 config_ldif_resp( Operation *op, SlapReply *rs )
3005 {
3006         if ( rs->sr_type == REP_SEARCH ) {
3007                 setup_cookie *sc = op->o_callback->sc_private;
3008
3009                 sc->cfb->cb_got_ldif = 1;
3010                 /* Does the frontend exist? */
3011                 if ( !sc->got_frontend ) {
3012                         if ( !strncmp( rs->sr_entry->e_nname.bv_val,
3013                                 "olcDatabase", STRLENOF( "olcDatabase" ))) {
3014                                 if ( strncmp( rs->sr_entry->e_nname.bv_val +
3015                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
3016                                         STRLENOF( "={-1}frontend" ))) {
3017                                         struct berval rdn;
3018                                         int i = op->o_noop;
3019                                         sc->ca->be = frontendDB;
3020                                         sc->ca->bi = frontendDB->bd_info;
3021                                         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
3022                                         rdn.bv_val = sc->ca->log;
3023                                         rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3024                                                 "%s=" SLAP_X_ORDERED_FMT "%s",
3025                                                 cfAd_database->ad_cname.bv_val, -1,
3026                                                 sc->ca->bi->bi_type);
3027                                         op->o_noop = 1;
3028                                         sc->frontend = config_build_entry( op, rs,
3029                                                 sc->cfb->cb_root, sc->ca, &rdn, &CFOC_DATABASE,
3030                                                 sc->ca->be->be_cf_ocs );
3031                                         op->o_noop = i;
3032                                         sc->got_frontend++;
3033                                 } else {
3034                                         sc->got_frontend++;
3035                                         goto ok;
3036                                 }
3037                         }
3038                 }
3039                 /* Does the configDB exist? */
3040                 if ( sc->got_frontend && !sc->got_config &&
3041                         !strncmp( rs->sr_entry->e_nname.bv_val,
3042                         "olcDatabase", STRLENOF( "olcDatabase" ))) {
3043                         if ( strncmp( rs->sr_entry->e_nname.bv_val +
3044                                 STRLENOF( "olcDatabase" ), "={0}config",
3045                                 STRLENOF( "={0}config" ))) {
3046                                 struct berval rdn;
3047                                 int i = op->o_noop;
3048                                 sc->ca->be = LDAP_STAILQ_FIRST( &backendDB );
3049                                 sc->ca->bi = sc->ca->be->bd_info;
3050                                 rdn.bv_val = sc->ca->log;
3051                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3052                                         "%s=" SLAP_X_ORDERED_FMT "%s",
3053                                         cfAd_database->ad_cname.bv_val, 0,
3054                                         sc->ca->bi->bi_type);
3055                                 op->o_noop = 1;
3056                                 sc->config = config_build_entry( op, rs, sc->cfb->cb_root,
3057                                         sc->ca, &rdn, &CFOC_DATABASE, sc->ca->be->be_cf_ocs );
3058                                 op->o_noop = i;
3059                         }
3060                         sc->got_config++;
3061                 }
3062
3063 ok:
3064                 rs->sr_err = config_add_internal( sc->cfb, rs->sr_entry, sc->ca, NULL, NULL, NULL );
3065                 if ( rs->sr_err != LDAP_SUCCESS ) {
3066                         Debug( LDAP_DEBUG_ANY, "config error processing %s: %s\n",
3067                                 rs->sr_entry->e_name.bv_val, sc->ca->cr_msg, 0 );
3068                 }
3069         }
3070         return rs->sr_err;
3071 }
3072
3073 /* Configure and read the underlying back-ldif store */
3074 static int
3075 config_setup_ldif( BackendDB *be, const char *dir, int readit ) {
3076         CfBackInfo *cfb = be->be_private;
3077         ConfigArgs c = {0};
3078         ConfigTable *ct;
3079         char *argv[3];
3080         int rc = 0;
3081         setup_cookie sc;
3082         slap_callback cb = { NULL, config_ldif_resp, NULL, NULL };
3083         Connection conn = {0};
3084         OperationBuffer opbuf;
3085         Operation *op;
3086         SlapReply rs = {REP_RESULT};
3087         Filter filter = { LDAP_FILTER_PRESENT };
3088         struct berval filterstr = BER_BVC("(objectclass=*)");
3089         struct stat st;
3090
3091         /* Is the config directory available? */
3092         if ( stat( dir, &st ) < 0 ) {
3093                 /* No, so don't bother using the backing store.
3094                  * All changes will be in-memory only.
3095                  */
3096                 return 0;
3097         }
3098                 
3099         cfb->cb_db.bd_info = backend_info( "ldif" );
3100         if ( !cfb->cb_db.bd_info )
3101                 return 0;       /* FIXME: eventually this will be a fatal error */
3102
3103         if ( backend_db_init( "ldif", &cfb->cb_db, -1, NULL ) == NULL )
3104                 return 1;
3105
3106         cfb->cb_db.be_suffix = be->be_suffix;
3107         cfb->cb_db.be_nsuffix = be->be_nsuffix;
3108
3109         /* The suffix is always "cn=config". The underlying DB's rootdn
3110          * is always the same as the suffix.
3111          */
3112         cfb->cb_db.be_rootdn = be->be_suffix[0];
3113         cfb->cb_db.be_rootndn = be->be_nsuffix[0];
3114
3115         ber_str2bv( dir, 0, 1, &cfdir );
3116
3117         c.be = &cfb->cb_db;
3118         c.fname = "slapd";
3119         c.argc = 2;
3120         argv[0] = "directory";
3121         argv[1] = (char *)dir;
3122         argv[2] = NULL;
3123         c.argv = argv;
3124         c.reply.err = 0;
3125         c.reply.msg[0] = 0;
3126         c.table = Cft_Database;
3127
3128         ct = config_find_keyword( c.be->be_cf_ocs->co_table, &c );
3129         if ( !ct )
3130                 return 1;
3131
3132         if ( config_add_vals( ct, &c ))
3133                 return 1;
3134
3135         if ( backend_startup_one( &cfb->cb_db, &c.reply ))
3136                 return 1;
3137
3138         if ( readit ) {
3139                 void *thrctx = ldap_pvt_thread_pool_context();
3140                 int prev_DN_strict;
3141
3142                 connection_fake_init( &conn, &opbuf, thrctx );
3143                 op = &opbuf.ob_op;
3144
3145                 filter.f_desc = slap_schema.si_ad_objectClass;
3146
3147                 op->o_tag = LDAP_REQ_SEARCH;
3148
3149                 op->ors_filter = &filter;
3150                 op->ors_filterstr = filterstr;
3151                 op->ors_scope = LDAP_SCOPE_SUBTREE;
3152
3153                 op->o_dn = c.be->be_rootdn;
3154                 op->o_ndn = c.be->be_rootndn;
3155
3156                 op->o_req_dn = be->be_suffix[0];
3157                 op->o_req_ndn = be->be_nsuffix[0];
3158
3159                 op->ors_tlimit = SLAP_NO_LIMIT;
3160                 op->ors_slimit = SLAP_NO_LIMIT;
3161
3162                 op->ors_attrs = slap_anlist_all_attributes;
3163                 op->ors_attrsonly = 0;
3164
3165                 op->o_callback = &cb;
3166                 sc.cfb = cfb;
3167                 sc.ca = &c;
3168                 cb.sc_private = &sc;
3169                 sc.got_frontend = 0;
3170                 sc.got_config = 0;
3171                 sc.frontend = NULL;
3172                 sc.config = NULL;
3173
3174                 op->o_bd = &cfb->cb_db;
3175                 
3176                 /* Allow unknown attrs in DNs */
3177                 prev_DN_strict = slap_DN_strict;
3178                 slap_DN_strict = 0;
3179
3180                 rc = op->o_bd->be_search( op, &rs );
3181
3182                 /* Restore normal DN validation */
3183                 slap_DN_strict = prev_DN_strict;
3184
3185                 op->o_tag = LDAP_REQ_ADD;
3186                 if ( rc == LDAP_SUCCESS && sc.frontend ) {
3187                         op->ora_e = sc.frontend;
3188                         rc = op->o_bd->be_add( op, &rs );
3189                 }
3190                 if ( rc == LDAP_SUCCESS && sc.config ) {
3191                         op->ora_e = sc.config;
3192                         rc = op->o_bd->be_add( op, &rs );
3193                 }
3194                 ldap_pvt_thread_pool_context_reset( thrctx );
3195         }
3196
3197         /* ITS#4194 - only use if it's present, or we're converting. */
3198         if ( !readit || rc == LDAP_SUCCESS )
3199                 cfb->cb_use_ldif = 1;
3200
3201         return rc;
3202 }
3203
3204 static int
3205 CfOc_cmp( const void *c1, const void *c2 ) {
3206         const ConfigOCs *co1 = c1;
3207         const ConfigOCs *co2 = c2;
3208
3209         return ber_bvcmp( co1->co_name, co2->co_name );
3210 }
3211
3212 int
3213 config_register_schema(ConfigTable *ct, ConfigOCs *ocs) {
3214         int i;
3215
3216         i = init_config_attrs( ct );
3217         if ( i ) return i;
3218
3219         /* set up the objectclasses */
3220         i = init_config_ocs( ocs );
3221         if ( i ) return i;
3222
3223         for (i=0; ocs[i].co_def; i++) {
3224                 if ( ocs[i].co_oc ) {
3225                         ocs[i].co_name = &ocs[i].co_oc->soc_cname;
3226                         if ( !ocs[i].co_table )
3227                                 ocs[i].co_table = ct;
3228                         avl_insert( &CfOcTree, &ocs[i], CfOc_cmp, avl_dup_error );
3229                 }
3230         }
3231         return 0;
3232 }
3233
3234 int
3235 read_config(const char *fname, const char *dir) {
3236         BackendDB *be;
3237         CfBackInfo *cfb;
3238         const char *cfdir, *cfname;
3239         int rc;
3240
3241         /* Setup the config backend */
3242         be = backend_db_init( "config", NULL, 0, NULL );
3243         if ( !be )
3244                 return 1;
3245
3246         cfb = be->be_private;
3247         be->be_dfltaccess = ACL_NONE;
3248
3249         /* If no .conf, or a dir was specified, setup the dir */
3250         if ( !fname || dir ) {
3251                 if ( dir ) {
3252                         /* If explicitly given, check for existence */
3253                         struct stat st;
3254
3255                         if ( stat( dir, &st ) < 0 ) {
3256                                 Debug( LDAP_DEBUG_ANY,
3257                                         "invalid config directory %s, error %d\n",
3258                                                 dir, errno, 0 );
3259                                 return 1;
3260                         }
3261                         cfdir = dir;
3262                 } else {
3263                         cfdir = SLAPD_DEFAULT_CONFIGDIR;
3264                 }
3265                 /* if fname is defaulted, try reading .d */
3266                 rc = config_setup_ldif( be, cfdir, !fname );
3267
3268                 if ( rc ) {
3269                         /* It may be OK if the base object doesn't exist yet. */
3270                         if ( rc != LDAP_NO_SUCH_OBJECT )
3271                                 return 1;
3272                         /* ITS#4194: But if dir was specified and no fname,
3273                          * then we were supposed to read the dir. Unless we're
3274                          * trying to slapadd the dir...
3275                          */
3276                         if ( dir && !fname ) {
3277                                 if ( slapMode & (SLAP_SERVER_MODE|SLAP_TOOL_READMAIN|SLAP_TOOL_READONLY))
3278                                         return 1;
3279                                 /* Assume it's slapadd with a config dir, let it continue */
3280                                 rc = 0;
3281                                 cfb->cb_got_ldif = 1;
3282                                 cfb->cb_use_ldif = 1;
3283                                 goto done;
3284                         }
3285                 }
3286
3287                 /* If we read the config from back-ldif, nothing to do here */
3288                 if ( cfb->cb_got_ldif ) {
3289                         rc = 0;
3290                         goto done;
3291                 }
3292         }
3293
3294         if ( fname )
3295                 cfname = fname;
3296         else
3297                 cfname = SLAPD_DEFAULT_CONFIGFILE;
3298
3299         rc = read_config_file(cfname, 0, NULL, config_back_cf_table);
3300
3301         if ( rc == 0 )
3302                 ber_str2bv( cfname, 0, 1, &cfb->cb_config->c_file );
3303
3304 done:
3305         if ( rc == 0 && BER_BVISNULL( &frontendDB->be_schemadn ) ) {
3306                 ber_str2bv( SLAPD_SCHEMA_DN, STRLENOF( SLAPD_SCHEMA_DN ), 1,
3307                         &frontendDB->be_schemadn );
3308                 rc = dnNormalize( 0, NULL, NULL, &frontendDB->be_schemadn, &frontendDB->be_schemandn, NULL );
3309                 if ( rc != LDAP_SUCCESS ) {
3310                         Debug(LDAP_DEBUG_ANY, "read_config: "
3311                                 "unable to normalize default schema DN \"%s\"\n",
3312                                 frontendDB->be_schemadn.bv_val, 0, 0 );
3313                         /* must not happen */
3314                         assert( 0 );
3315                 }
3316         }
3317         return rc;
3318 }
3319
3320 static int
3321 config_back_bind( Operation *op, SlapReply *rs )
3322 {
3323         if ( be_isroot_pw( op ) ) {
3324                 ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ));
3325                 /* frontend sends result */
3326                 return LDAP_SUCCESS;
3327         }
3328
3329         rs->sr_err = LDAP_INVALID_CREDENTIALS;
3330         send_ldap_result( op, rs );
3331
3332         return rs->sr_err;
3333 }
3334
3335 static int
3336 config_send( Operation *op, SlapReply *rs, CfEntryInfo *ce, int depth )
3337 {
3338         int rc = 0;
3339
3340         if ( test_filter( op, ce->ce_entry, op->ors_filter ) == LDAP_COMPARE_TRUE )
3341         {
3342                 rs->sr_attrs = op->ors_attrs;
3343                 rs->sr_entry = ce->ce_entry;
3344                 rs->sr_flags = 0;
3345                 rc = send_search_entry( op, rs );
3346         }
3347         if ( op->ors_scope == LDAP_SCOPE_SUBTREE ) {
3348                 if ( ce->ce_kids ) {
3349                         rc = config_send( op, rs, ce->ce_kids, 1 );
3350                         if ( rc ) return rc;
3351                 }
3352                 if ( depth ) {
3353                         for (ce=ce->ce_sibs; ce; ce=ce->ce_sibs) {
3354                                 rc = config_send( op, rs, ce, 0 );
3355                                 if ( rc ) break;
3356                         }
3357                 }
3358         }
3359         return rc;
3360 }
3361
3362 static ConfigTable *
3363 config_find_table( ConfigOCs **colst, int nocs, AttributeDescription *ad,
3364         ConfigArgs *ca )
3365 {
3366         int i, j;
3367
3368         for (j=0; j<nocs; j++) {
3369                 for (i=0; colst[j]->co_table[i].name; i++)
3370                         if ( colst[j]->co_table[i].ad == ad ) {
3371                                 ca->table = colst[j]->co_type;
3372                                 return &colst[j]->co_table[i];
3373                         }
3374         }
3375         return NULL;
3376 }
3377
3378 /* Sort the attributes of the entry according to the order defined
3379  * in the objectclass, with required attributes occurring before
3380  * allowed attributes. For any attributes with sequencing dependencies
3381  * (e.g., rootDN must be defined after suffix) the objectclass must
3382  * list the attributes in the desired sequence.
3383  */
3384 static void
3385 sort_attrs( Entry *e, ConfigOCs **colst, int nocs )
3386 {
3387         Attribute *a, *head = NULL, *tail = NULL, **prev;
3388         int i, j;
3389
3390         for (i=0; i<nocs; i++) {
3391                 if ( colst[i]->co_oc->soc_required ) {
3392                         AttributeType **at = colst[i]->co_oc->soc_required;
3393                         for (j=0; at[j]; j++) {
3394                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3395                                         prev = &(*prev)->a_next, a=a->a_next) {
3396                                         if ( a->a_desc == at[j]->sat_ad ) {
3397                                                 *prev = a->a_next;
3398                                                 if (!head) {
3399                                                         head = a;
3400                                                         tail = a;
3401                                                 } else {
3402                                                         tail->a_next = a;
3403                                                         tail = a;
3404                                                 }
3405                                                 break;
3406                                         }
3407                                 }
3408                         }
3409                 }
3410                 if ( colst[i]->co_oc->soc_allowed ) {
3411                         AttributeType **at = colst[i]->co_oc->soc_allowed;
3412                         for (j=0; at[j]; j++) {
3413                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3414                                         prev = &(*prev)->a_next, a=a->a_next) {
3415                                         if ( a->a_desc == at[j]->sat_ad ) {
3416                                                 *prev = a->a_next;
3417                                                 if (!head) {
3418                                                         head = a;
3419                                                         tail = a;
3420                                                 } else {
3421                                                         tail->a_next = a;
3422                                                         tail = a;
3423                                                 }
3424                                                 break;
3425                                         }
3426                                 }
3427                         }
3428                 }
3429         }
3430         if ( tail ) {
3431                 tail->a_next = e->e_attrs;
3432                 e->e_attrs = head;
3433         }
3434 }
3435
3436 static int
3437 check_vals( ConfigTable *ct, ConfigArgs *ca, void *ptr, int isAttr )
3438 {
3439         Attribute *a = NULL;
3440         AttributeDescription *ad;
3441         BerVarray vals;
3442
3443         int i, rc = 0;
3444
3445         if ( isAttr ) {
3446                 a = ptr;
3447                 ad = a->a_desc;
3448                 vals = a->a_vals;
3449         } else {
3450                 Modifications *ml = ptr;
3451                 ad = ml->sml_desc;
3452                 vals = ml->sml_values;
3453         }
3454
3455         if ( a && ( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL )) {
3456                 rc = ordered_value_sort( a, 1 );
3457                 if ( rc ) {
3458                         snprintf(ca->cr_msg, sizeof( ca->cr_msg ), "ordered_value_sort failed on attr %s\n",
3459                                 ad->ad_cname.bv_val );
3460                         return rc;
3461                 }
3462         }
3463         for ( i=0; vals[i].bv_val; i++ ) {
3464                 ca->line = vals[i].bv_val;
3465                 if (( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL ) &&
3466                         ca->line[0] == '{' ) {
3467                         char *idx = strchr( ca->line, '}' );
3468                         if ( idx ) ca->line = idx+1;
3469                 }
3470                 rc = config_parse_vals( ct, ca, i );
3471                 if ( rc ) {
3472                         break;
3473                 }
3474         }
3475         return rc;
3476 }
3477
3478 static int
3479 config_rename_attr( SlapReply *rs, Entry *e, struct berval *rdn,
3480         Attribute **at )
3481 {
3482         struct berval rtype, rval;
3483         Attribute *a;
3484         AttributeDescription *ad = NULL;
3485
3486         dnRdn( &e->e_name, rdn );
3487         rval.bv_val = strchr(rdn->bv_val, '=' ) + 1;
3488         rval.bv_len = rdn->bv_len - (rval.bv_val - rdn->bv_val);
3489         rtype.bv_val = rdn->bv_val;
3490         rtype.bv_len = rval.bv_val - rtype.bv_val - 1;
3491
3492         /* Find attr */
3493         slap_bv2ad( &rtype, &ad, &rs->sr_text );
3494         a = attr_find( e->e_attrs, ad );
3495         if (!a ) return LDAP_NAMING_VIOLATION;
3496         *at = a;
3497
3498         return 0;
3499 }
3500
3501 static void
3502 config_rename_kids( CfEntryInfo *ce )
3503 {
3504         CfEntryInfo *ce2;
3505         struct berval rdn, nrdn;
3506
3507         for (ce2 = ce->ce_kids; ce2; ce2 = ce2->ce_sibs) {
3508                 dnRdn ( &ce2->ce_entry->e_name, &rdn );
3509                 dnRdn ( &ce2->ce_entry->e_nname, &nrdn );
3510                 free( ce2->ce_entry->e_name.bv_val );
3511                 free( ce2->ce_entry->e_nname.bv_val );
3512                 build_new_dn( &ce2->ce_entry->e_name, &ce->ce_entry->e_name,
3513                         &rdn, NULL );
3514                 build_new_dn( &ce2->ce_entry->e_nname, &ce->ce_entry->e_nname,
3515                         &nrdn, NULL );
3516                 config_rename_kids( ce2 );
3517         }
3518 }
3519
3520 static int
3521 config_rename_one( Operation *op, SlapReply *rs, Entry *e,
3522         CfEntryInfo *parent, Attribute *a, struct berval *newrdn,
3523         struct berval *nnewrdn, int use_ldif )
3524 {
3525         char *ptr1;
3526         int rc = 0;
3527         struct berval odn, ondn;
3528
3529         odn = e->e_name;
3530         ondn = e->e_nname;
3531         build_new_dn( &e->e_name, &parent->ce_entry->e_name, newrdn, NULL );
3532         build_new_dn( &e->e_nname, &parent->ce_entry->e_nname, nnewrdn, NULL );
3533
3534         /* Replace attr */
3535         free( a->a_vals[0].bv_val );
3536         ptr1 = strchr( newrdn->bv_val, '=' ) + 1;
3537         a->a_vals[0].bv_len = newrdn->bv_len - (ptr1 - newrdn->bv_val);
3538         a->a_vals[0].bv_val = ch_malloc( a->a_vals[0].bv_len + 1 );
3539         strcpy( a->a_vals[0].bv_val, ptr1 );
3540
3541         if ( a->a_nvals != a->a_vals ) {
3542                 free( a->a_nvals[0].bv_val );
3543                 ptr1 = strchr( nnewrdn->bv_val, '=' ) + 1;
3544                 a->a_nvals[0].bv_len = nnewrdn->bv_len - (ptr1 - nnewrdn->bv_val);
3545                 a->a_nvals[0].bv_val = ch_malloc( a->a_nvals[0].bv_len + 1 );
3546                 strcpy( a->a_nvals[0].bv_val, ptr1 );
3547         }
3548         if ( use_ldif ) {
3549                 CfBackInfo *cfb = (CfBackInfo *)op->o_bd->be_private;
3550                 BackendDB *be = op->o_bd;
3551                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
3552                 struct berval dn, ndn, xdn, xndn;
3553
3554                 op->o_bd = &cfb->cb_db;
3555
3556                 /* Save current rootdn; use the underlying DB's rootdn */
3557                 dn = op->o_dn;
3558                 ndn = op->o_ndn;
3559                 xdn = op->o_req_dn;
3560                 xndn = op->o_req_ndn;
3561                 op->o_dn = op->o_bd->be_rootdn;
3562                 op->o_ndn = op->o_bd->be_rootndn;
3563                 op->o_req_dn = odn;
3564                 op->o_req_ndn = ondn;
3565
3566                 scp = op->o_callback;
3567                 op->o_callback = &sc;
3568                 op->orr_newrdn = *newrdn;
3569                 op->orr_nnewrdn = *nnewrdn;
3570                 op->orr_newSup = NULL;
3571                 op->orr_nnewSup = NULL;
3572                 op->orr_deleteoldrdn = 1;
3573                 op->orr_modlist = NULL;
3574                 slap_modrdn2mods( op, rs );
3575                 slap_mods_opattrs( op, &op->orr_modlist, 1 );
3576                 rc = op->o_bd->be_modrdn( op, rs );
3577                 slap_mods_free( op->orr_modlist, 1 );
3578
3579                 op->o_bd = be;
3580                 op->o_callback = scp;
3581                 op->o_dn = dn;
3582                 op->o_ndn = ndn;
3583                 op->o_req_dn = xdn;
3584                 op->o_req_ndn = xndn;
3585         }
3586         free( odn.bv_val );
3587         free( ondn.bv_val );
3588         if ( e->e_private )
3589                 config_rename_kids( e->e_private );
3590         return rc;
3591 }
3592
3593 static int
3594 config_renumber_one( Operation *op, SlapReply *rs, CfEntryInfo *parent, 
3595         Entry *e, int idx, int tailindex, int use_ldif )
3596 {
3597         struct berval ival, newrdn, nnewrdn;
3598         struct berval rdn;
3599         Attribute *a;
3600         char ibuf[32], *ptr1, *ptr2 = NULL;
3601         int rc = 0;
3602
3603         rc = config_rename_attr( rs, e, &rdn, &a );
3604         if ( rc ) return rc;
3605
3606         ival.bv_val = ibuf;
3607         ival.bv_len = snprintf( ibuf, sizeof( ibuf ), SLAP_X_ORDERED_FMT, idx );
3608         if ( ival.bv_len >= sizeof( ibuf ) ) {
3609                 return LDAP_NAMING_VIOLATION;
3610         }
3611         
3612         newrdn.bv_len = rdn.bv_len + ival.bv_len;
3613         newrdn.bv_val = ch_malloc( newrdn.bv_len+1 );
3614
3615         if ( tailindex ) {
3616                 ptr1 = lutil_strncopy( newrdn.bv_val, rdn.bv_val, rdn.bv_len );
3617                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3618         } else {
3619                 int xlen;
3620                 ptr2 = ber_bvchr( &rdn, '}' );
3621                 if ( ptr2 ) {
3622                         ptr2++;
3623                 } else {
3624                         ptr2 = rdn.bv_val + a->a_desc->ad_cname.bv_len + 1;
3625                 }
3626                 xlen = rdn.bv_len - (ptr2 - rdn.bv_val);
3627                 ptr1 = lutil_strncopy( newrdn.bv_val, a->a_desc->ad_cname.bv_val,
3628                         a->a_desc->ad_cname.bv_len );
3629                 *ptr1++ = '=';
3630                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3631                 ptr1 = lutil_strncopy( ptr1, ptr2, xlen );
3632                 *ptr1 = '\0';
3633         }
3634
3635         /* Do the equivalent of ModRDN */
3636         /* Replace DN / NDN */
3637         newrdn.bv_len = ptr1 - newrdn.bv_val;
3638         rdnNormalize( 0, NULL, NULL, &newrdn, &nnewrdn, NULL );
3639         rc = config_rename_one( op, rs, e, parent, a, &newrdn, &nnewrdn, use_ldif );
3640
3641         free( nnewrdn.bv_val );
3642         free( newrdn.bv_val );
3643         return rc;
3644 }
3645
3646 static int
3647 check_name_index( CfEntryInfo *parent, ConfigType ce_type, Entry *e,
3648         SlapReply *rs, int *renum, int *ibase )
3649 {
3650         CfEntryInfo *ce;
3651         int index = -1, gotindex = 0, nsibs, rc = 0;
3652         int renumber = 0, tailindex = 0, isfrontend = 0, isconfig = 0;
3653         char *ptr1, *ptr2 = NULL;
3654         struct berval rdn;
3655
3656         if ( renum ) *renum = 0;
3657
3658         /* These entries don't get indexed/renumbered */
3659         if ( ce_type == Cft_Global ) return 0;
3660         if ( ce_type == Cft_Schema && parent->ce_type == Cft_Global ) return 0;
3661
3662         if ( ce_type == Cft_Module )
3663                 tailindex = 1;
3664
3665         /* See if the rdn has an index already */
3666         dnRdn( &e->e_name, &rdn );
3667         if ( ce_type == Cft_Database ) {
3668                 if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("frontend"),
3669                                 "frontend", STRLENOF("frontend") )) 
3670                         isfrontend = 1;
3671                 else if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("config"),
3672                                 "config", STRLENOF("config") )) 
3673                         isconfig = 1;
3674         }
3675         ptr1 = ber_bvchr( &e->e_name, '{' );
3676         if ( ptr1 && ptr1 - e->e_name.bv_val < rdn.bv_len ) {
3677                 char    *next;
3678                 ptr2 = strchr( ptr1, '}' );
3679                 if (!ptr2 || ptr2 - e->e_name.bv_val > rdn.bv_len)
3680                         return LDAP_NAMING_VIOLATION;
3681                 if ( ptr2-ptr1 == 1)
3682                         return LDAP_NAMING_VIOLATION;
3683                 gotindex = 1;
3684                 index = strtol( ptr1 + 1, &next, 10 );
3685                 if ( next == ptr1 + 1 || next[ 0 ] != '}' ) {
3686                         return LDAP_NAMING_VIOLATION;
3687                 }
3688                 if ( index < 0 ) {
3689                         /* Special case, we allow -1 for the frontendDB */
3690                         if ( index != -1 || !isfrontend )
3691                                 return LDAP_NAMING_VIOLATION;
3692                 }
3693                 if ( isconfig && index != 0 ){
3694                         return LDAP_NAMING_VIOLATION;
3695                 }
3696         }
3697
3698         /* count related kids */
3699         for (nsibs=0, ce=parent->ce_kids; ce; ce=ce->ce_sibs) {
3700                 if ( ce->ce_type == ce_type ) nsibs++;
3701         }
3702
3703         /* account for -1 frontend */
3704         if ( ce_type == Cft_Database )
3705                 nsibs--;
3706
3707         if ( index != nsibs ) {
3708                 if ( gotindex ) {
3709                         if ( index < nsibs ) {
3710                                 if ( tailindex ) return LDAP_NAMING_VIOLATION;
3711                                 /* Siblings need to be renumbered */
3712                                 if ( index != -1 || !isfrontend )
3713                                         renumber = 1;
3714                         }
3715                 }
3716                 /* config DB is always "0" */
3717                 if ( isconfig && index == -1 ) {
3718                         index = 0;
3719                 }
3720                 if ( !isfrontend && index == -1 ) {
3721                         index = nsibs;
3722                 }
3723
3724                 /* just make index = nsibs */
3725                 if ( !renumber ) {
3726                         rc = config_renumber_one( NULL, rs, parent, e, index, tailindex, 0 );
3727                 }
3728         }
3729         if ( ibase ) *ibase = index;
3730         if ( renum ) *renum = renumber;
3731         return rc;
3732 }
3733
3734 static int
3735 count_oc( ObjectClass *oc, ConfigOCs ***copp, int *nocs )
3736 {
3737         ConfigOCs       co, *cop;
3738         ObjectClass     **sups;
3739
3740         co.co_name = &oc->soc_cname;
3741         cop = avl_find( CfOcTree, &co, CfOc_cmp );
3742         if ( cop ) {
3743                 int     i;
3744
3745                 /* check for duplicates */
3746                 for ( i = 0; i < *nocs; i++ ) {
3747                         if ( *copp && (*copp)[i] == cop ) {
3748                                 break;
3749                         }
3750                 }
3751
3752                 if ( i == *nocs ) {
3753                         ConfigOCs **tmp = ch_realloc( *copp, (*nocs + 1)*sizeof( ConfigOCs * ) );
3754                         if ( tmp == NULL ) {
3755                                 return -1;
3756                         }
3757                         *copp = tmp;
3758                         (*copp)[*nocs] = cop;
3759                         (*nocs)++;
3760                 }
3761         }
3762
3763         for ( sups = oc->soc_sups; sups && *sups; sups++ ) {
3764                 if ( count_oc( *sups, copp, nocs ) ) {
3765                         return -1;
3766                 }
3767         }
3768
3769         return 0;
3770 }
3771
3772 static ConfigOCs **
3773 count_ocs( Attribute *oc_at, int *nocs )
3774 {
3775         int             i;
3776         ConfigOCs       **colst = NULL;
3777
3778         *nocs = 0;
3779
3780         for ( i = 0; !BER_BVISNULL( &oc_at->a_nvals[i] ); i++ )
3781                 /* count attrs */ ;
3782
3783         for ( ; i--; ) {
3784                 ObjectClass     *oc = oc_bvfind( &oc_at->a_nvals[i] );
3785
3786                 assert( oc != NULL );
3787                 if ( count_oc( oc, &colst, nocs ) ) {
3788                         ch_free( colst );
3789                         return NULL;
3790                 }
3791         }
3792
3793         return colst;
3794 }
3795
3796 static int
3797 cfAddSchema( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3798 {
3799         ConfigFile *cfo;
3800
3801         /* This entry is hardcoded, don't re-parse it */
3802         if ( p->ce_type == Cft_Global ) {
3803                 cfn = p->ce_private;
3804                 ca->private = cfn;
3805                 return LDAP_COMPARE_TRUE;
3806         }
3807         if ( p->ce_type != Cft_Schema )
3808                 return LDAP_CONSTRAINT_VIOLATION;
3809
3810         cfn = ch_calloc( 1, sizeof(ConfigFile) );
3811         ca->private = cfn;
3812         cfo = p->ce_private;
3813         cfn->c_sibs = cfo->c_kids;
3814         cfo->c_kids = cfn;
3815         return LDAP_SUCCESS;
3816 }
3817
3818 static int
3819 cfAddDatabase( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3820 {
3821         if ( p->ce_type != Cft_Global ) {
3822                 return LDAP_CONSTRAINT_VIOLATION;
3823         }
3824         ca->be = frontendDB;    /* just to get past check_vals */
3825         return LDAP_SUCCESS;
3826 }
3827
3828 static int
3829 cfAddBackend( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3830 {
3831         if ( p->ce_type != Cft_Global ) {
3832                 return LDAP_CONSTRAINT_VIOLATION;
3833         }
3834         return LDAP_SUCCESS;
3835 }
3836
3837 static int
3838 cfAddModule( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3839 {
3840         if ( p->ce_type != Cft_Global ) {
3841                 return LDAP_CONSTRAINT_VIOLATION;
3842         }
3843         return LDAP_SUCCESS;
3844 }
3845
3846 static int
3847 cfAddOverlay( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3848 {
3849         if ( p->ce_type != Cft_Database ) {
3850                 return LDAP_CONSTRAINT_VIOLATION;
3851         }
3852         ca->be = p->ce_be;
3853         return LDAP_SUCCESS;
3854 }
3855
3856 static void
3857 schema_destroy_one( ConfigArgs *ca, ConfigOCs **colst, int nocs,
3858         CfEntryInfo *p )
3859 {
3860         ConfigTable *ct;
3861         ConfigFile *cfo;
3862         AttributeDescription *ad;
3863         const char *text;
3864
3865         ca->valx = -1;
3866         ca->line = NULL;
3867         if ( cfn->c_cr_head ) {
3868                 struct berval bv = BER_BVC("olcDitContentRules");
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_oc_head ) {
3875                 struct berval bv = BER_BVC("olcObjectClasses");
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_at_head ) {
3882                 struct berval bv = BER_BVC("olcAttributeTypes");
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         if ( cfn->c_om_head ) {
3889                 struct berval bv = BER_BVC("olcObjectIdentifier");
3890                 ad = NULL;
3891                 slap_bv2ad( &bv, &ad, &text );
3892                 ct = config_find_table( colst, nocs, ad, ca );
3893                 config_del_vals( ct, ca );
3894         }
3895         cfo = p->ce_private;
3896         cfo->c_kids = cfn->c_sibs;
3897         ch_free( cfn );
3898 }
3899
3900 static int
3901 config_add_oc( ConfigOCs **cop, CfEntryInfo *last, Entry *e, ConfigArgs *ca )
3902 {
3903         int             rc = LDAP_CONSTRAINT_VIOLATION;
3904         ObjectClass     **ocp;
3905
3906         if ( (*cop)->co_ldadd ) {
3907                 rc = (*cop)->co_ldadd( last, e, ca );
3908                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3909                         return rc;
3910                 }
3911         }
3912
3913         for ( ocp = (*cop)->co_oc->soc_sups; ocp && *ocp; ocp++ ) {
3914                 ConfigOCs       co = { 0 };
3915
3916                 co.co_name = &(*ocp)->soc_cname;
3917                 *cop = avl_find( CfOcTree, &co, CfOc_cmp );
3918                 if ( *cop == NULL ) {
3919                         return rc;
3920                 }
3921
3922                 rc = config_add_oc( cop, last, e, ca );
3923                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3924                         return rc;
3925                 }
3926         }
3927
3928         return rc;
3929 }
3930
3931 /* Parse an LDAP entry into config directives */
3932 static int
3933 config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca, SlapReply *rs,
3934         int *renum, Operation *op )
3935 {
3936         CfEntryInfo     *ce, *last = NULL;
3937         ConfigOCs       co, *coptr, **colst;
3938         Attribute       *a, *oc_at, *soc_at;
3939         int             i, ibase = -1, nocs, rc = 0;
3940         struct berval   pdn;
3941         ConfigTable     *ct;
3942         char            *ptr, *log_prefix = op ? op->o_log_prefix : "";
3943
3944         memset( ca, 0, sizeof(ConfigArgs));
3945
3946         /* Make sure parent exists and entry does not. But allow
3947          * Databases and Overlays to be inserted. Don't do any
3948          * auto-renumbering if manageDSAit control is present.
3949          */
3950         ce = config_find_base( cfb->cb_root, &e->e_nname, &last );
3951         if ( ce ) {
3952                 if ( ( op && op->o_managedsait ) ||
3953                         ( ce->ce_type != Cft_Database && ce->ce_type != Cft_Overlay &&
3954                           ce->ce_type != Cft_Module ) )
3955                 {
3956                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3957                                 "DN=\"%s\" already exists\n",
3958                                 log_prefix, e->e_name.bv_val, 0 );
3959                         return LDAP_ALREADY_EXISTS;
3960                 }
3961         }
3962
3963         dnParent( &e->e_nname, &pdn );
3964
3965         /* If last is NULL, the new entry is the root/suffix entry, 
3966          * otherwise last should be the parent.
3967          */
3968         if ( last && !dn_match( &last->ce_entry->e_nname, &pdn ) ) {
3969                 if ( rs ) {
3970                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3971                 }
3972                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3973                         "DN=\"%s\" not child of DN=\"%s\"\n",
3974                         log_prefix, e->e_name.bv_val,
3975                         last->ce_entry->e_name.bv_val );
3976                 return LDAP_NO_SUCH_OBJECT;
3977         }
3978
3979         if ( op ) {
3980                 /* No parent, must be root. This will never happen... */
3981                 if ( !last && !be_isroot( op ) && !be_shadow_update( op ) ) {
3982                         return LDAP_NO_SUCH_OBJECT;
3983                 }
3984
3985                 if ( last && !access_allowed( op, last->ce_entry,
3986                         slap_schema.si_ad_children, NULL, ACL_WADD, NULL ) )
3987                 {
3988                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3989                                 "DN=\"%s\" no write access to \"children\" of parent\n",
3990                                 log_prefix, e->e_name.bv_val, 0 );
3991                         return LDAP_INSUFFICIENT_ACCESS;
3992                 }
3993         }
3994
3995         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
3996         if ( !oc_at ) {
3997                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3998                         "DN=\"%s\" no objectClass\n",
3999                         log_prefix, e->e_name.bv_val, 0 );
4000                 return LDAP_OBJECT_CLASS_VIOLATION;
4001         }
4002
4003         soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4004         if ( !soc_at ) {
4005                 ObjectClass     *soc = NULL;
4006                 char            textbuf[ SLAP_TEXT_BUFLEN ];
4007                 const char      *text = textbuf;
4008
4009                 /* FIXME: check result */
4010                 rc = structural_class( oc_at->a_nvals, &soc, NULL,
4011                         &text, textbuf, sizeof(textbuf), NULL );
4012                 if ( rc != LDAP_SUCCESS ) {
4013                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4014                                 "DN=\"%s\" no structural objectClass (%s)\n",
4015                                 log_prefix, e->e_name.bv_val, text );
4016                         return rc;
4017                 }
4018                 attr_merge_one( e, slap_schema.si_ad_structuralObjectClass, &soc->soc_cname, NULL );
4019                 soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4020                 if ( soc_at == NULL ) {
4021                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4022                                 "DN=\"%s\" no structural objectClass; "
4023                                 "unable to merge computed class %s\n",
4024                                 log_prefix, e->e_name.bv_val,
4025                                 soc->soc_cname.bv_val );
4026                         return LDAP_OBJECT_CLASS_VIOLATION;
4027                 }
4028
4029                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4030                         "DN=\"%s\" no structural objectClass; "
4031                         "computed objectClass %s merged\n",
4032                         log_prefix, e->e_name.bv_val,
4033                         soc->soc_cname.bv_val );
4034         }
4035
4036         /* Fake the coordinates based on whether we're part of an
4037          * LDAP Add or if reading the config dir
4038          */
4039         if ( rs ) {
4040                 ca->fname = "slapd";
4041                 ca->lineno = 0;
4042         } else {
4043                 ca->fname = cfdir.bv_val;
4044                 ca->lineno = 1;
4045         }
4046         ca->ca_op = op;
4047
4048         co.co_name = &soc_at->a_nvals[0];
4049         coptr = avl_find( CfOcTree, &co, CfOc_cmp );
4050         if ( coptr == NULL ) {
4051                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4052                         "DN=\"%s\" no structural objectClass in configuration table\n",
4053                         log_prefix, e->e_name.bv_val, 0 );
4054                 return LDAP_OBJECT_CLASS_VIOLATION;
4055         }
4056
4057         /* Only the root can be Cft_Global, everything else must
4058          * have a parent. Only limited nesting arrangements are allowed.
4059          */
4060         rc = LDAP_CONSTRAINT_VIOLATION;
4061         if ( coptr->co_type == Cft_Global && !last ) {
4062                 cfn = cfb->cb_config;
4063                 ca->private = cfn;
4064                 ca->be = frontendDB;    /* just to get past check_vals */
4065                 rc = LDAP_SUCCESS;
4066         }
4067
4068         /* Check whether the Add is allowed by its parent, and do
4069          * any necessary arg setup
4070          */
4071         if ( last ) {
4072                 rc = config_add_oc( &coptr, last, e, ca );
4073                 if ( rc == LDAP_CONSTRAINT_VIOLATION ) {
4074                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4075                                 "DN=\"%s\" no structural objectClass add function\n",
4076                                 log_prefix, e->e_name.bv_val, 0 );
4077                         return LDAP_OBJECT_CLASS_VIOLATION;
4078                 }
4079         }
4080
4081         colst = count_ocs( oc_at, &nocs );
4082
4083         /* Add the entry but don't parse it, we already have its contents */
4084         if ( rc == LDAP_COMPARE_TRUE ) {
4085                 rc = LDAP_SUCCESS;
4086                 goto ok;
4087         }
4088
4089         if ( rc != LDAP_SUCCESS )
4090                 goto done_noop;
4091
4092         /* Parse all the values and check for simple syntax errors before
4093          * performing any set actions.
4094          *
4095          * If doing an LDAPadd, check for indexed names and any necessary
4096          * renaming/renumbering. Entries that don't need indexed names are
4097          * ignored. Entries that need an indexed name and arrive without one
4098          * are assigned to the end. Entries that arrive with an index may
4099          * cause the following entries to be renumbered/bumped down.
4100          *
4101          * Note that "pseudo-indexed" entries (cn=Include{xx}, cn=Module{xx})
4102          * don't allow Adding an entry with an index that's already in use.
4103          * This is flagged as an error (LDAP_ALREADY_EXISTS) up above.
4104          *
4105          * These entries can have auto-assigned indexes (appended to the end)
4106          * but only the other types support auto-renumbering of siblings.
4107          */
4108         {
4109                 rc = check_name_index( last, coptr->co_type, e, rs, renum,
4110                         &ibase );
4111                 if ( rc ) {
4112                         goto done_noop;
4113                 }
4114                 if ( renum && *renum && coptr->co_type != Cft_Database &&
4115                         coptr->co_type != Cft_Overlay )
4116                 {
4117                         snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
4118                                 "operation requires sibling renumbering" );
4119                         rc = LDAP_UNWILLING_TO_PERFORM;
4120                         goto done_noop;
4121                 }
4122         }
4123
4124         init_config_argv( ca );
4125
4126         /* Make sure we process attrs in the required order */
4127         sort_attrs( e, colst, nocs );
4128
4129         for ( a = e->e_attrs; a; a = a->a_next ) {
4130                 if ( a == oc_at ) continue;
4131                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4132                 if ( !ct ) continue;    /* user data? */
4133                 rc = check_vals( ct, ca, a, 1 );
4134                 if ( rc ) goto done_noop;
4135         }
4136
4137         /* Basic syntax checks are OK. Do the actual settings. */
4138         for ( a=e->e_attrs; a; a=a->a_next ) {
4139                 if ( a == oc_at ) continue;
4140                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4141                 if ( !ct ) continue;    /* user data? */
4142                 for (i=0; a->a_vals[i].bv_val; i++) {
4143                         char *iptr = NULL;
4144                         ca->line = a->a_vals[i].bv_val;
4145                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED ) {
4146                                 ptr = strchr( ca->line, '}' );
4147                                 if ( ptr ) {
4148                                         iptr = strchr( ca->line, '{' );
4149                                         ca->line = ptr+1;
4150                                 }
4151                         }
4152                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED_SIB ) {
4153                                 if ( iptr ) {
4154                                         ca->valx = strtol( iptr+1, NULL, 0 );
4155                                 } else {
4156                                         ca->valx = -1;
4157                                 }
4158                         } else {
4159                                 ca->valx = i;
4160                         }
4161                         rc = config_parse_add( ct, ca, i );
4162                         if ( rc ) {
4163                                 rc = LDAP_OTHER;
4164                                 goto done;
4165                         }
4166                 }
4167         }
4168 ok:
4169         /* Newly added databases and overlays need to be started up */
4170         if ( CONFIG_ONLINE_ADD( ca )) {
4171                 if ( colst[0]->co_type == Cft_Database ) {
4172                         rc = backend_startup_one( ca->be, &ca->reply );
4173
4174                 } else if ( colst[0]->co_type == Cft_Overlay ) {
4175                         if ( ca->bi->bi_db_open ) {
4176                                 BackendInfo *bi_orig = ca->be->bd_info;
4177                                 ca->be->bd_info = ca->bi;
4178                                 rc = ca->bi->bi_db_open( ca->be, &ca->reply );
4179                                 ca->be->bd_info = bi_orig;
4180                         }
4181                 }
4182                 if ( rc ) {
4183                         if (ca->cr_msg[0] == '\0')
4184                                 snprintf( ca->cr_msg, sizeof( ca->cr_msg ), "<%s> failed startup", ca->argv[0] );
4185
4186                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
4187                                 ca->log, ca->cr_msg, ca->argv[1] );
4188                         rc = LDAP_OTHER;
4189                         goto done;
4190                 }
4191         }
4192
4193         ca->valx = ibase;
4194         ce = ch_calloc( 1, sizeof(CfEntryInfo) );
4195         ce->ce_parent = last;
4196         ce->ce_entry = entry_dup( e );
4197         ce->ce_entry->e_private = ce;
4198         ce->ce_type = colst[0]->co_type;
4199         ce->ce_be = ca->be;
4200         ce->ce_bi = ca->bi;
4201         ce->ce_private = ca->private;
4202         ca->ca_entry = ce->ce_entry;
4203         if ( !last ) {
4204                 cfb->cb_root = ce;
4205         } else if ( last->ce_kids ) {
4206                 CfEntryInfo *c2, **cprev;
4207
4208                 /* Advance to first of this type */
4209                 cprev = &last->ce_kids;
4210                 for ( c2 = *cprev; c2 && c2->ce_type < ce->ce_type; ) {
4211                         cprev = &c2->ce_sibs;
4212                         c2 = c2->ce_sibs;
4213                 }
4214                 /* Account for the (-1) frontendDB entry */
4215                 if ( ce->ce_type == Cft_Database ) {
4216                         if ( ca->be == frontendDB )
4217                                 ibase = 0;
4218                         else if ( ibase != -1 )
4219                                 ibase++;
4220                 }
4221                 /* Append */
4222                 if ( ibase < 0 ) {
4223                         for (c2 = *cprev; c2 && c2->ce_type == ce->ce_type;) {
4224                                 cprev = &c2->ce_sibs;
4225                                 c2 = c2->ce_sibs;
4226                         }
4227                 } else {
4228                 /* Insert */
4229                         int i;
4230                         for ( i=0; i<ibase; i++ ) {
4231                                 c2 = *cprev;
4232                                 cprev = &c2->ce_sibs;
4233                         }
4234                 }
4235                 ce->ce_sibs = *cprev;
4236                 *cprev = ce;
4237         } else {
4238                 last->ce_kids = ce;
4239         }
4240
4241 done:
4242         if ( rc ) {
4243                 if ( (colst[0]->co_type == Cft_Database) && ca->be ) {
4244                         if ( ca->be != frontendDB )
4245                                 backend_destroy_one( ca->be, 1 );
4246                 } else if ( (colst[0]->co_type == Cft_Overlay) && ca->bi ) {
4247                         overlay_destroy_one( ca->be, (slap_overinst *)ca->bi );
4248                 } else if ( colst[0]->co_type == Cft_Schema ) {
4249                         schema_destroy_one( ca, colst, nocs, last );
4250                 }
4251         }
4252 done_noop:
4253
4254         ch_free( ca->argv );
4255         if ( colst ) ch_free( colst );
4256         return rc;
4257 }
4258
4259 #define BIGTMP  10000
4260 static int
4261 config_rename_add( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4262         int base, int rebase, int max, int use_ldif )
4263 {
4264         CfEntryInfo *ce2, *ce3, *cetmp = NULL, *cerem = NULL;
4265         ConfigType etype = ce->ce_type;
4266         int count = 0, rc = 0;
4267
4268         /* Reverse ce list */
4269         for (ce2 = ce->ce_sibs;ce2;ce2 = ce3) {
4270                 if (ce2->ce_type != etype) {
4271                         cerem = ce2;
4272                         break;
4273                 }
4274                 ce3 = ce2->ce_sibs;
4275                 ce2->ce_sibs = cetmp;
4276                 cetmp = ce2;
4277                 count++;
4278                 if ( max && count >= max ) {
4279                         cerem = ce3;
4280                         break;
4281                 }
4282         }
4283
4284         /* Move original to a temp name until increments are done */
4285         if ( rebase ) {
4286                 ce->ce_entry->e_private = NULL;
4287                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4288                         base+BIGTMP, 0, use_ldif );
4289                 ce->ce_entry->e_private = ce;
4290         }
4291         /* start incrementing */
4292         for (ce2=cetmp; ce2; ce2=ce3) {
4293                 ce3 = ce2->ce_sibs;
4294                 ce2->ce_sibs = cerem;
4295                 cerem = ce2;
4296                 if ( rc == 0 ) 
4297                         rc = config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4298                                 count+base, 0, use_ldif );
4299                 count--;
4300         }
4301         if ( rebase )
4302                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4303                         base, 0, use_ldif );
4304         return rc;
4305 }
4306
4307 static int
4308 config_rename_del( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4309         CfEntryInfo *ce2, int old, int use_ldif )
4310 {
4311         int count = 0;
4312
4313         /* Renumber original to a temp value */
4314         ce->ce_entry->e_private = NULL;
4315         config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4316                 old+BIGTMP, 0, use_ldif );
4317         ce->ce_entry->e_private = ce;
4318
4319         /* start decrementing */
4320         for (; ce2 != ce; ce2=ce2->ce_sibs) {
4321                 config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4322                         count+old, 0, use_ldif );
4323                 count++;
4324         }
4325         return config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4326                 count+old, 0, use_ldif );
4327 }
4328
4329 /* Parse an LDAP entry into config directives, then store in underlying
4330  * database.
4331  */
4332 static int
4333 config_back_add( Operation *op, SlapReply *rs )
4334 {
4335         CfBackInfo *cfb;
4336         int renumber;
4337         ConfigArgs ca;
4338
4339         if ( !access_allowed( op, op->ora_e, slap_schema.si_ad_entry,
4340                 NULL, ACL_WADD, NULL )) {
4341                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4342                 goto out;
4343         }
4344
4345         cfb = (CfBackInfo *)op->o_bd->be_private;
4346
4347         /* add opattrs for syncprov */
4348         {
4349                 char textbuf[SLAP_TEXT_BUFLEN];
4350                 size_t textlen = sizeof textbuf;
4351                 rs->sr_err = entry_schema_check(op, op->ora_e, NULL, 0, 1,
4352                         &rs->sr_text, textbuf, sizeof( textbuf ) );
4353                 if ( rs->sr_err != LDAP_SUCCESS )
4354                         goto out;
4355                 rs->sr_err = slap_add_opattrs( op, &rs->sr_text, textbuf, textlen, 1 );
4356                 if ( rs->sr_err != LDAP_SUCCESS ) {
4357                         Debug( LDAP_DEBUG_TRACE,
4358                                 LDAP_XSTRING(config_back_add) ": entry failed op attrs add: "
4359                                 "%s (%d)\n", rs->sr_text, rs->sr_err, 0 );
4360                         goto out;
4361                 }
4362         }
4363
4364         ldap_pvt_thread_pool_pause( &connection_pool );
4365
4366         /* Strategy:
4367          * 1) check for existence of entry
4368          * 2) check for sibling renumbering
4369          * 3) perform internal add
4370          * 4) perform any necessary renumbering
4371          * 5) store entry in underlying database
4372          */
4373         rs->sr_err = config_add_internal( cfb, op->ora_e, &ca, rs, &renumber, op );
4374         if ( rs->sr_err != LDAP_SUCCESS ) {
4375                 rs->sr_text = ca.cr_msg;
4376                 goto out2;
4377         }
4378
4379         if ( renumber ) {
4380                 CfEntryInfo *ce = ca.ca_entry->e_private;
4381                 req_add_s addr = op->oq_add;
4382                 op->o_tag = LDAP_REQ_MODRDN;
4383                 rs->sr_err = config_rename_add( op, rs, ce, ca.valx, 0, 0, cfb->cb_use_ldif );
4384                 op->o_tag = LDAP_REQ_ADD;
4385                 op->oq_add = addr;
4386                 if ( rs->sr_err != LDAP_SUCCESS ) {
4387                         goto out2;
4388                 }
4389         }
4390
4391         if ( cfb->cb_use_ldif ) {
4392                 BackendDB *be = op->o_bd;
4393                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4394                 struct berval dn, ndn;
4395
4396                 op->o_bd = &cfb->cb_db;
4397
4398                 /* Save current rootdn; use the underlying DB's rootdn */
4399                 dn = op->o_dn;
4400                 ndn = op->o_ndn;
4401                 op->o_dn = op->o_bd->be_rootdn;
4402                 op->o_ndn = op->o_bd->be_rootndn;
4403
4404                 scp = op->o_callback;
4405                 op->o_callback = &sc;
4406                 op->o_bd->be_add( op, rs );
4407                 op->o_bd = be;
4408                 op->o_callback = scp;
4409                 op->o_dn = dn;
4410                 op->o_ndn = ndn;
4411         }
4412
4413 out2:;
4414         ldap_pvt_thread_pool_resume( &connection_pool );
4415
4416 out:;
4417         send_ldap_result( op, rs );
4418         slap_graduate_commit_csn( op );
4419         return rs->sr_err;
4420 }
4421
4422 typedef struct delrec {
4423         struct delrec *next;
4424         int nidx;
4425         int idx[1];
4426 } delrec;
4427
4428 static int
4429 config_modify_add( ConfigTable *ct, ConfigArgs *ca, AttributeDescription *ad,
4430         int i )
4431 {
4432         int rc;
4433
4434         if (ad->ad_type->sat_flags & SLAP_AT_ORDERED &&
4435                 ca->line[0] == '{' )
4436         {
4437                 char *ptr = strchr( ca->line + 1, '}' );
4438                 if ( ptr ) {
4439                         char    *next;
4440
4441                         ca->valx = strtol( ca->line + 1, &next, 0 );
4442                         if ( next == ca->line + 1 || next[ 0 ] != '}' ) {
4443                                 return LDAP_OTHER;
4444                         }
4445                         ca->line = ptr+1;
4446                 }
4447         }
4448         rc = config_parse_add( ct, ca, i );
4449         if ( rc ) {
4450                 rc = LDAP_OTHER;
4451         }
4452         return rc;
4453 }
4454
4455 static int
4456 config_modify_internal( CfEntryInfo *ce, Operation *op, SlapReply *rs,
4457         ConfigArgs *ca )
4458 {
4459         int rc = LDAP_UNWILLING_TO_PERFORM;
4460         Modifications *ml;
4461         Entry *e = ce->ce_entry;
4462         Attribute *save_attrs = e->e_attrs, *oc_at, *s, *a;
4463         ConfigTable *ct;
4464         ConfigOCs **colst;
4465         int i, nocs;
4466         char *ptr;
4467         delrec *dels = NULL, *deltail = NULL;
4468
4469         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
4470         if ( !oc_at ) return LDAP_OBJECT_CLASS_VIOLATION;
4471
4472         colst = count_ocs( oc_at, &nocs );
4473
4474         /* make sure add/del flags are clear; should always be true */
4475         for ( s = save_attrs; s; s = s->a_next ) {
4476                 s->a_flags &= ~(SLAP_ATTR_IXADD|SLAP_ATTR_IXDEL);
4477         }
4478
4479         e->e_attrs = attrs_dup( e->e_attrs );
4480
4481         init_config_argv( ca );
4482         ca->be = ce->ce_be;
4483         ca->bi = ce->ce_bi;
4484         ca->private = ce->ce_private;
4485         ca->ca_entry = e;
4486         ca->fname = "slapd";
4487         ca->ca_op = op;
4488         strcpy( ca->log, "back-config" );
4489
4490         for (ml = op->orm_modlist; ml; ml=ml->sml_next) {
4491                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4492                 switch (ml->sml_op) {
4493                 case LDAP_MOD_DELETE:
4494                 case LDAP_MOD_REPLACE: {
4495                         BerVarray vals = NULL, nvals = NULL;
4496                         int *idx = NULL;
4497                         if ( ct && ( ct->arg_type & ARG_NO_DELETE )) {
4498                                 rc = LDAP_OTHER;
4499                                 snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot delete %s",
4500                                         ml->sml_desc->ad_cname.bv_val );
4501                                 goto out_noop;
4502                         }
4503                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4504                                 vals = ml->sml_values;
4505                                 nvals = ml->sml_nvalues;
4506                                 ml->sml_values = NULL;
4507                                 ml->sml_nvalues = NULL;
4508                         }
4509                         /* If we're deleting by values, remember the indexes of the
4510                          * values we deleted.
4511                          */
4512                         if ( ct && ml->sml_values ) {
4513                                 delrec *d;
4514                                 for (i=0; ml->sml_values[i].bv_val; i++);
4515                                 d = ch_malloc( sizeof(delrec) + (i - 1)* sizeof(int));
4516                                 d->nidx = i;
4517                                 d->next = NULL;
4518                                 if ( dels ) {
4519                                         deltail->next = d;
4520                                 } else {
4521                                         dels = d;
4522                                 }
4523                                 deltail = d;
4524                                 idx = d->idx;
4525                         }
4526                         rc = modify_delete_vindex(e, &ml->sml_mod,
4527                                 get_permissiveModify(op),
4528                                 &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg), idx );
4529                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4530                                 ml->sml_values = vals;
4531                                 ml->sml_nvalues = nvals;
4532                         }
4533                         if ( !vals )
4534                                 break;
4535                         }
4536                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4537
4538                 case LDAP_MOD_ADD:
4539                 case SLAP_MOD_SOFTADD: {
4540                         int mop = ml->sml_op;
4541                         int navals = -1;
4542                         ml->sml_op = LDAP_MOD_ADD;
4543                         if ( ct ) {
4544                                 if ( ct->arg_type & ARG_NO_INSERT ) {
4545                                         Attribute *a = attr_find( e->e_attrs, ml->sml_desc );
4546                                         if ( a ) {
4547                                                 for (i = 0; a->a_vals[i].bv_val; i++ );
4548                                                 navals = i;
4549                                         }
4550                                 }
4551                                 for ( i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++ ) {
4552                                         if ( ml->sml_values[i].bv_val[0] == '{' &&
4553                                                 navals >= 0 )
4554                                         {
4555                                                 char    *next, *val = ml->sml_values[i].bv_val + 1;
4556                                                 int     j;
4557
4558                                                 j = strtol( val, &next, 0 );
4559                                                 if ( next == val || next[ 0 ] != '}' || j < navals ) {
4560                                                         rc = LDAP_OTHER;
4561                                                         snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot insert %s",
4562                                                                 ml->sml_desc->ad_cname.bv_val );
4563                                                         goto out_noop;
4564                                                 }
4565                                         }
4566                                         rc = check_vals( ct, ca, ml, 0 );
4567                                         if ( rc ) goto out_noop;
4568                                 }
4569                         }
4570                         rc = modify_add_values(e, &ml->sml_mod,
4571                                    get_permissiveModify(op),
4572                                    &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4573
4574                         /* If value already exists, show success here
4575                          * and ignore this operation down below.
4576                          */
4577                         if ( mop == SLAP_MOD_SOFTADD ) {
4578                                 if ( rc == LDAP_TYPE_OR_VALUE_EXISTS )
4579                                         rc = LDAP_SUCCESS;
4580                                 else
4581                                         mop = LDAP_MOD_ADD;
4582                         }
4583                         ml->sml_op = mop;
4584                         break;
4585                         }
4586
4587                         break;
4588                 case LDAP_MOD_INCREMENT:        /* FIXME */
4589                         break;
4590                 default:
4591                         break;
4592                 }
4593                 if(rc != LDAP_SUCCESS) break;
4594         }
4595         
4596         if ( rc == LDAP_SUCCESS) {
4597                 /* check that the entry still obeys the schema */
4598                 rc = entry_schema_check(op, e, NULL, 0, 0,
4599                         &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4600                 if ( rc ) goto out_noop;
4601         }
4602         /* Basic syntax checks are OK. Do the actual settings. */
4603         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4604                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4605                 if ( !ct ) continue;
4606
4607                 s = attr_find( save_attrs, ml->sml_desc );
4608                 a = attr_find( e->e_attrs, ml->sml_desc );
4609
4610                 switch (ml->sml_op) {
4611                 case LDAP_MOD_DELETE:
4612                 case LDAP_MOD_REPLACE: {
4613                         BerVarray vals = NULL, nvals = NULL;
4614                         delrec *d = NULL;
4615
4616                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4617                                 vals = ml->sml_values;
4618                                 nvals = ml->sml_nvalues;
4619                                 ml->sml_values = NULL;
4620                                 ml->sml_nvalues = NULL;
4621                         }
4622
4623                         if ( ml->sml_values )
4624                                 d = dels;
4625
4626                         /* If we didn't delete the whole attribute */
4627                         if ( ml->sml_values && a ) {
4628                                 struct berval *mvals;
4629                                 int j;
4630
4631                                 if ( ml->sml_nvalues )
4632                                         mvals = ml->sml_nvalues;
4633                                 else
4634                                         mvals = ml->sml_values;
4635
4636                                 /* use the indexes we saved up above */
4637                                 for (i=0; i < d->nidx; i++) {
4638                                         struct berval bv = *mvals++;
4639                                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED &&
4640                                                 bv.bv_val[0] == '{' ) {
4641                                                 ptr = strchr( bv.bv_val, '}' ) + 1;
4642                                                 bv.bv_len -= ptr - bv.bv_val;
4643                                                 bv.bv_val = ptr;
4644                                         }
4645                                         ca->line = bv.bv_val;
4646                                         ca->valx = d->idx[i];
4647                                         rc = config_del_vals( ct, ca );
4648                                         if ( rc != LDAP_SUCCESS ) break;
4649                                         if ( s )
4650                                                 s->a_flags |= SLAP_ATTR_IXDEL;
4651                                         for (j=i+1; j < d->nidx; j++)
4652                                                 if ( d->idx[j] >d->idx[i] )
4653                                                         d->idx[j]--;
4654                                 }
4655                         } else {
4656                                 ca->valx = -1;
4657                                 ca->line = NULL;
4658                                 rc = config_del_vals( ct, ca );
4659                                 if ( rc ) rc = LDAP_OTHER;
4660                                 if ( s )
4661                                         s->a_flags |= SLAP_ATTR_IXDEL;
4662                         }
4663                         if ( ml->sml_values ) {
4664                                 d = d->next;
4665                                 ch_free( dels );
4666                                 dels = d;
4667                         }
4668                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4669                                 ml->sml_values = vals;
4670                                 ml->sml_nvalues = nvals;
4671                         }
4672                         if ( !vals || rc != LDAP_SUCCESS )
4673                                 break;
4674                         }
4675                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4676
4677                 case LDAP_MOD_ADD:
4678                         for (i=0; ml->sml_values[i].bv_val; i++) {
4679                                 ca->line = ml->sml_values[i].bv_val;
4680                                 ca->valx = -1;
4681                                 rc = config_modify_add( ct, ca, ml->sml_desc, i );
4682                                 if ( rc )
4683                                         goto out;
4684                                 a->a_flags |= SLAP_ATTR_IXADD;
4685                         }
4686                         break;
4687                 }
4688         }
4689
4690 out:
4691         /* Undo for a failed operation */
4692         if ( rc != LDAP_SUCCESS ) {
4693                 for ( s = save_attrs; s; s = s->a_next ) {
4694                         if ( s->a_flags & SLAP_ATTR_IXDEL ) {
4695                                 s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4696                                 ct = config_find_table( colst, nocs, s->a_desc, ca );
4697                                 a = attr_find( e->e_attrs, s->a_desc );
4698                                 if ( a ) {
4699                                         /* clear the flag so the add check below will skip it */
4700                                         a->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4701                                         ca->valx = -1;
4702                                         ca->line = NULL;
4703                                         config_del_vals( ct, ca );
4704                                 }
4705                                 for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4706                                         ca->line = s->a_vals[i].bv_val;
4707                                         ca->valx = -1;
4708                                         config_modify_add( ct, ca, s->a_desc, i );
4709                                 }
4710                         }
4711                 }
4712                 for ( a = e->e_attrs; a; a = a->a_next ) {
4713                         if ( a->a_flags & SLAP_ATTR_IXADD ) {
4714                                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4715                                 ca->valx = -1;
4716                                 ca->line = NULL;
4717                                 config_del_vals( ct, ca );
4718                                 s = attr_find( save_attrs, a->a_desc );
4719                                 if ( s ) {
4720                                         s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4721                                         for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4722                                                 ca->line = s->a_vals[i].bv_val;
4723                                                 ca->valx = -1;
4724                                                 config_modify_add( ct, ca, s->a_desc, i );
4725                                         }
4726                                 }
4727                         }
4728                 }
4729         }
4730
4731         if ( ca->cleanup )
4732                 ca->cleanup( ca );
4733 out_noop:
4734         if ( rc == LDAP_SUCCESS ) {
4735                 attrs_free( save_attrs );
4736         } else {
4737                 attrs_free( e->e_attrs );
4738                 e->e_attrs = save_attrs;
4739         }
4740         ch_free( ca->argv );
4741         if ( colst ) ch_free( colst );
4742         while( dels ) {
4743                 deltail = dels->next;
4744                 ch_free( dels );
4745                 dels = deltail;
4746         }
4747
4748         return rc;
4749 }
4750
4751 static int
4752 config_back_modify( Operation *op, SlapReply *rs )
4753 {
4754         CfBackInfo *cfb;
4755         CfEntryInfo *ce, *last;
4756         Modifications *ml;
4757         ConfigArgs ca = {0};
4758         struct berval rdn;
4759         char *ptr;
4760         AttributeDescription *rad = NULL;
4761
4762         cfb = (CfBackInfo *)op->o_bd->be_private;
4763
4764         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4765         if ( !ce ) {
4766                 if ( last )
4767                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4768                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4769                 goto out;
4770         }
4771
4772         if ( !acl_check_modlist( op, ce->ce_entry, op->orm_modlist )) {
4773                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4774                 goto out;
4775         }
4776
4777         /* Get type of RDN */
4778         rdn = ce->ce_entry->e_nname;
4779         ptr = strchr( rdn.bv_val, '=' );
4780         rdn.bv_len = ptr - rdn.bv_val;
4781         slap_bv2ad( &rdn, &rad, &rs->sr_text );
4782
4783         /* Some basic validation... */
4784         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4785                 /* Don't allow Modify of RDN; must use ModRdn for that. */
4786                 if ( ml->sml_desc == rad ) {
4787                         rs->sr_err = LDAP_NOT_ALLOWED_ON_RDN;
4788                         rs->sr_text = "Use modrdn to change the entry name";
4789                         goto out;
4790                 }
4791         }
4792
4793         slap_mods_opattrs( op, &op->orm_modlist, 1 );
4794
4795         if ( !slapd_shutdown )
4796                 ldap_pvt_thread_pool_pause( &connection_pool );
4797
4798         /* Strategy:
4799          * 1) perform the Modify on the cached Entry.
4800          * 2) verify that the Entry still satisfies the schema.
4801          * 3) perform the individual config operations.
4802          * 4) store Modified entry in underlying LDIF backend.
4803          */
4804         rs->sr_err = config_modify_internal( ce, op, rs, &ca );
4805         if ( rs->sr_err ) {
4806                 rs->sr_text = ca.cr_msg;
4807         } else if ( cfb->cb_use_ldif ) {
4808                 BackendDB *be = op->o_bd;
4809                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4810                 struct berval dn, ndn;
4811
4812                 op->o_bd = &cfb->cb_db;
4813
4814                 dn = op->o_dn;
4815                 ndn = op->o_ndn;
4816                 op->o_dn = op->o_bd->be_rootdn;
4817                 op->o_ndn = op->o_bd->be_rootndn;
4818
4819                 scp = op->o_callback;
4820                 op->o_callback = &sc;
4821                 op->o_bd->be_modify( op, rs );
4822                 op->o_bd = be;
4823                 op->o_callback = scp;
4824                 op->o_dn = dn;
4825                 op->o_ndn = ndn;
4826         }
4827
4828         if ( !slapd_shutdown )
4829                 ldap_pvt_thread_pool_resume( &connection_pool );
4830 out:
4831         send_ldap_result( op, rs );
4832         slap_graduate_commit_csn( op );
4833         return rs->sr_err;
4834 }
4835
4836 static int
4837 config_back_modrdn( Operation *op, SlapReply *rs )
4838 {
4839         CfBackInfo *cfb;
4840         CfEntryInfo *ce, *last;
4841         struct berval rdn;
4842         int ixold, ixnew;
4843
4844         cfb = (CfBackInfo *)op->o_bd->be_private;
4845
4846         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4847         if ( !ce ) {
4848                 if ( last )
4849                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4850                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4851                 goto out;
4852         }
4853         if ( !access_allowed( op, ce->ce_entry, slap_schema.si_ad_entry,
4854                 NULL, ACL_WRITE, NULL )) {
4855                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4856                 goto out;
4857         }
4858         { Entry *parent;
4859                 if ( ce->ce_parent )
4860                         parent = ce->ce_parent->ce_entry;
4861                 else
4862                         parent = (Entry *)&slap_entry_root;
4863                 if ( !access_allowed( op, parent, slap_schema.si_ad_children,
4864                         NULL, ACL_WRITE, NULL )) {
4865                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4866                         goto out;
4867                 }
4868         }
4869
4870         /* We don't allow moving objects to new parents.
4871          * Generally we only allow reordering a set of ordered entries.
4872          */
4873         if ( op->orr_newSup ) {
4874                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4875                 goto out;
4876         }
4877
4878         /* If newRDN == oldRDN, quietly succeed */
4879         dnRdn( &op->o_req_ndn, &rdn );
4880         if ( dn_match( &rdn, &op->orr_nnewrdn )) {
4881                 rs->sr_err = LDAP_SUCCESS;
4882                 goto out;
4883         }
4884
4885         /* Current behavior, subject to change as needed:
4886          *
4887          * For backends and overlays, we only allow renumbering.
4888          * For schema, we allow renaming with the same number.
4889          * Otherwise, the op is not allowed.
4890          */
4891
4892         if ( ce->ce_type == Cft_Schema ) {
4893                 char *ptr1, *ptr2;
4894                 int len;
4895
4896                 /* Can't alter the main cn=schema entry */
4897                 if ( ce->ce_parent->ce_type == Cft_Global ) {
4898                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4899                         rs->sr_text = "renaming not allowed for this entry";
4900                         goto out;
4901                 }
4902
4903                 /* We could support this later if desired */
4904                 ptr1 = ber_bvchr( &rdn, '}' );
4905                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4906                 len = ptr1 - rdn.bv_val;
4907                 if ( len != ptr2 - op->orr_newrdn.bv_val ||
4908                         strncmp( rdn.bv_val, op->orr_newrdn.bv_val, len )) {
4909                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4910                         rs->sr_text = "schema reordering not supported";
4911                         goto out;
4912                 }
4913         } else if ( ce->ce_type == Cft_Database ||
4914                 ce->ce_type == Cft_Overlay ) {
4915                 char *ptr1, *ptr2, *iptr1, *iptr2;
4916                 int len1, len2;
4917
4918                 iptr2 = ber_bvchr( &op->orr_newrdn, '=' ) + 1;
4919                 if ( *iptr2 != '{' ) {
4920                         rs->sr_err = LDAP_NAMING_VIOLATION;
4921                         rs->sr_text = "new ordering index is required";
4922                         goto out;
4923                 }
4924                 iptr2++;
4925                 iptr1 = ber_bvchr( &rdn, '{' ) + 1;
4926                 ptr1 = ber_bvchr( &rdn, '}' );
4927                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4928                 if ( !ptr2 ) {
4929                         rs->sr_err = LDAP_NAMING_VIOLATION;
4930                         rs->sr_text = "new ordering index is required";
4931                         goto out;
4932                 }
4933
4934                 len1 = ptr1 - rdn.bv_val;
4935                 len2 = ptr2 - op->orr_newrdn.bv_val;
4936
4937                 if ( rdn.bv_len - len1 != op->orr_newrdn.bv_len - len2 ||
4938                         strncmp( ptr1, ptr2, rdn.bv_len - len1 )) {
4939                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4940                         rs->sr_text = "changing database/overlay type not allowed";
4941                         goto out;
4942                 }
4943                 ixold = strtol( iptr1, NULL, 0 );
4944                 ixnew = strtol( iptr2, &ptr1, 0 );
4945                 if ( ptr1 != ptr2 || ixold < 0 || ixnew < 0 ) {
4946                         rs->sr_err = LDAP_NAMING_VIOLATION;
4947                         goto out;
4948                 }
4949                 /* config DB is always 0, cannot be changed */
4950                 if ( ce->ce_type == Cft_Database && ( ixold == 0 || ixnew == 0 )) {
4951                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
4952                         goto out;
4953                 }
4954         } else {
4955                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4956                 rs->sr_text = "renaming not supported for this entry";
4957                 goto out;
4958         }
4959
4960         ldap_pvt_thread_pool_pause( &connection_pool );
4961
4962         if ( ce->ce_type == Cft_Schema ) {
4963                 req_modrdn_s modr = op->oq_modrdn;
4964                 struct berval rdn;
4965                 Attribute *a;
4966                 rs->sr_err = config_rename_attr( rs, ce->ce_entry, &rdn, &a );
4967                 if ( rs->sr_err == LDAP_SUCCESS ) {
4968                         rs->sr_err = config_rename_one( op, rs, ce->ce_entry,
4969                                 ce->ce_parent, a, &op->orr_newrdn, &op->orr_nnewrdn,
4970                                 cfb->cb_use_ldif );
4971                 }
4972                 op->oq_modrdn = modr;
4973         } else {
4974                 CfEntryInfo *ce2, *cebase, **cprev, **cbprev, *ceold;
4975                 req_modrdn_s modr = op->oq_modrdn;
4976                 int i;
4977
4978                 /* Advance to first of this type */
4979                 cprev = &ce->ce_parent->ce_kids;
4980                 for ( ce2 = *cprev; ce2 && ce2->ce_type != ce->ce_type; ) {
4981                         cprev = &ce2->ce_sibs;
4982                         ce2 = ce2->ce_sibs;
4983                 }
4984                 /* Skip the -1 entry */
4985                 if ( ce->ce_type == Cft_Database ) {
4986                         cprev = &ce2->ce_sibs;
4987                         ce2 = ce2->ce_sibs;
4988                 }
4989                 cebase = ce2;
4990                 cbprev = cprev;
4991
4992                 /* Remove from old slot */
4993                 for ( ce2 = *cprev; ce2 && ce2 != ce; ce2 = ce2->ce_sibs )
4994                         cprev = &ce2->ce_sibs;
4995                 *cprev = ce->ce_sibs;
4996                 ceold = ce->ce_sibs;
4997
4998                 /* Insert into new slot */
4999                 cprev = cbprev;
5000                 for ( i=0; i<ixnew; i++ ) {
5001                         ce2 = *cprev;
5002                         if ( !ce2 )
5003                                 break;
5004                         cprev = &ce2->ce_sibs;
5005                 }
5006                 ce->ce_sibs = *cprev;
5007                 *cprev = ce;
5008
5009                 ixnew = i;
5010
5011                 /* NOTE: These should be encoded in the OC tables, not inline here */
5012                 if ( ce->ce_type == Cft_Database )
5013                         backend_db_move( ce->ce_be, ixnew );
5014                 else if ( ce->ce_type == Cft_Overlay )
5015                         overlay_move( ce->ce_be, (slap_overinst *)ce->ce_bi, ixnew );
5016                         
5017                 if ( ixold < ixnew ) {
5018                         rs->sr_err = config_rename_del( op, rs, ce, ceold, ixold,
5019                                 cfb->cb_use_ldif );
5020                 } else {
5021                         rs->sr_err = config_rename_add( op, rs, ce, ixnew, 1,
5022                                 ixold - ixnew, cfb->cb_use_ldif );
5023                 }
5024                 op->oq_modrdn = modr;
5025         }
5026
5027         ldap_pvt_thread_pool_resume( &connection_pool );
5028 out:
5029         send_ldap_result( op, rs );
5030         return rs->sr_err;
5031 }
5032
5033 static int
5034 config_back_delete( Operation *op, SlapReply *rs )
5035 {
5036         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, NULL );
5037         return rs->sr_err;
5038 }
5039
5040 static int
5041 config_back_search( Operation *op, SlapReply *rs )
5042 {
5043         CfBackInfo *cfb;
5044         CfEntryInfo *ce, *last;
5045         slap_mask_t mask;
5046
5047         cfb = (CfBackInfo *)op->o_bd->be_private;
5048
5049         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
5050         if ( !ce ) {
5051                 if ( last )
5052                         rs->sr_matched = last->ce_entry->e_name.bv_val;
5053                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
5054                 goto out;
5055         }
5056         if ( !access_allowed_mask( op, ce->ce_entry, slap_schema.si_ad_entry, NULL,
5057                 ACL_SEARCH, NULL, &mask ))
5058         {
5059                 if ( !ACL_GRANT( mask, ACL_DISCLOSE )) {
5060                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
5061                 } else {
5062                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
5063                 }
5064                 goto out;
5065         }
5066         switch ( op->ors_scope ) {
5067         case LDAP_SCOPE_BASE:
5068         case LDAP_SCOPE_SUBTREE:
5069                 config_send( op, rs, ce, 0 );
5070                 break;
5071                 
5072         case LDAP_SCOPE_ONELEVEL:
5073                 for (ce = ce->ce_kids; ce; ce=ce->ce_sibs) {
5074                         config_send( op, rs, ce, 1 );
5075                 }
5076                 break;
5077         }
5078                 
5079         rs->sr_err = LDAP_SUCCESS;
5080 out:
5081         send_ldap_result( op, rs );
5082         return 0;
5083 }
5084
5085 /* no-op, we never free entries */
5086 int config_entry_release(
5087         Operation *op,
5088         Entry *e,
5089         int rw )
5090 {
5091         if ( !e->e_private ) {
5092                 entry_free( e );
5093         }
5094         return LDAP_SUCCESS;
5095 }
5096
5097 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
5098  */
5099 int config_back_entry_get(
5100         Operation *op,
5101         struct berval *ndn,
5102         ObjectClass *oc,
5103         AttributeDescription *at,
5104         int rw,
5105         Entry **ent )
5106 {
5107         CfBackInfo *cfb;
5108         CfEntryInfo *ce, *last;
5109
5110         cfb = (CfBackInfo *)op->o_bd->be_private;
5111
5112         ce = config_find_base( cfb->cb_root, ndn, &last );
5113         if ( ce ) {
5114                 *ent = ce->ce_entry;
5115                 if ( *ent && oc && !is_entry_objectclass_or_sub( *ent, oc ) ) {
5116                         *ent = NULL;
5117                 }
5118         }
5119
5120         return ( *ent == NULL ? 1 : 0 );
5121 }
5122
5123 static void
5124 config_build_attrs( Entry *e, AttributeType **at, AttributeDescription *ad,
5125         ConfigTable *ct, ConfigArgs *c )
5126 {
5127         int i, rc;
5128
5129         for (; at && *at; at++) {
5130                 /* Skip the naming attr */
5131                 if ((*at)->sat_ad == ad || (*at)->sat_ad == slap_schema.si_ad_cn )
5132                         continue;
5133                 for (i=0;ct[i].name;i++) {
5134                         if (ct[i].ad == (*at)->sat_ad) {
5135                                 rc = config_get_vals(&ct[i], c);
5136                                 /* NOTE: tolerate that config_get_vals()
5137                                  * returns success with no values */
5138                                 if (rc == LDAP_SUCCESS && c->rvalue_vals != NULL ) {
5139                                         if ( c->rvalue_nvals )
5140                                                 attr_merge(e, ct[i].ad, c->rvalue_vals,
5141                                                         c->rvalue_nvals);
5142                                         else
5143                                                 attr_merge_normalize(e, ct[i].ad,
5144                                                         c->rvalue_vals, NULL);
5145                                         ber_bvarray_free( c->rvalue_nvals );
5146                                         ber_bvarray_free( c->rvalue_vals );
5147                                 }
5148                                 break;
5149                         }
5150                 }
5151         }
5152 }
5153
5154 Entry *
5155 config_build_entry( Operation *op, SlapReply *rs, CfEntryInfo *parent,
5156         ConfigArgs *c, struct berval *rdn, ConfigOCs *main, ConfigOCs *extra )
5157 {
5158         Entry *e = entry_alloc();
5159         CfEntryInfo *ce = ch_calloc( 1, sizeof(CfEntryInfo) );
5160         struct berval val;
5161         struct berval ad_name;
5162         AttributeDescription *ad = NULL;
5163         int rc;
5164         char *ptr;
5165         const char *text;
5166         Attribute *oc_at;
5167         struct berval pdn;
5168         ObjectClass *oc;
5169         CfEntryInfo *ceprev = NULL;
5170
5171         Debug( LDAP_DEBUG_TRACE, "config_build_entry: \"%s\"\n", rdn->bv_val, 0, 0);
5172         e->e_private = ce;
5173         ce->ce_entry = e;
5174         ce->ce_type = main->co_type;
5175         ce->ce_parent = parent;
5176         if ( parent ) {
5177                 pdn = parent->ce_entry->e_nname;
5178                 if ( parent->ce_kids )
5179                         for ( ceprev = parent->ce_kids; ceprev->ce_sibs &&
5180                                 ceprev->ce_type <= ce->ce_type;
5181                                 ceprev = ceprev->ce_sibs );
5182         } else {
5183                 BER_BVZERO( &pdn );
5184         }
5185
5186         ce->ce_private = c->private;
5187         ce->ce_be = c->be;
5188         ce->ce_bi = c->bi;
5189
5190         build_new_dn( &e->e_name, &pdn, rdn, NULL );
5191         ber_dupbv( &e->e_nname, &e->e_name );
5192
5193         attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5194                 main->co_name, NULL );
5195         if ( extra )
5196                 attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5197                         extra->co_name, NULL );
5198         ptr = strchr(rdn->bv_val, '=');
5199         ad_name.bv_val = rdn->bv_val;
5200         ad_name.bv_len = ptr - rdn->bv_val;
5201         rc = slap_bv2ad( &ad_name, &ad, &text );
5202         if ( rc ) {
5203                 return NULL;
5204         }
5205         val.bv_val = ptr+1;
5206         val.bv_len = rdn->bv_len - (val.bv_val - rdn->bv_val);
5207         attr_merge_normalize_one(e, ad, &val, NULL );
5208
5209         oc = main->co_oc;
5210         c->table = main->co_type;
5211         if ( oc->soc_required )
5212                 config_build_attrs( e, oc->soc_required, ad, main->co_table, c );
5213
5214         if ( oc->soc_allowed )
5215                 config_build_attrs( e, oc->soc_allowed, ad, main->co_table, c );
5216
5217         if ( extra ) {
5218                 oc = extra->co_oc;
5219                 c->table = extra->co_type;
5220                 if ( oc->soc_required )
5221                         config_build_attrs( e, oc->soc_required, ad, extra->co_table, c );
5222
5223                 if ( oc->soc_allowed )
5224                         config_build_attrs( e, oc->soc_allowed, ad, extra->co_table, c );
5225         }
5226
5227         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
5228         rc = structural_class(oc_at->a_vals, &oc, NULL, &text, c->cr_msg,
5229                 sizeof(c->cr_msg), op ? op->o_tmpmemctx : NULL );
5230         attr_merge_normalize_one(e, slap_schema.si_ad_structuralObjectClass, &oc->soc_cname, NULL );
5231         if ( op && !op->o_noop ) {
5232                 op->ora_e = e;
5233                 op->ora_modlist = NULL;
5234                 op->o_bd->be_add( op, rs );
5235                 if ( ( rs->sr_err != LDAP_SUCCESS ) 
5236                                 && (rs->sr_err != LDAP_ALREADY_EXISTS) ) {
5237                         return NULL;
5238                 }
5239         }
5240         if ( ceprev ) {
5241                 ce->ce_sibs = ceprev->ce_sibs;
5242                 ceprev->ce_sibs = ce;
5243         } else if ( parent ) {
5244                 ce->ce_sibs = parent->ce_kids;
5245                 parent->ce_kids = ce;
5246         }
5247
5248         return e;
5249 }
5250
5251 static int
5252 config_build_schema_inc( ConfigArgs *c, CfEntryInfo *ceparent,
5253         Operation *op, SlapReply *rs )
5254 {
5255         Entry *e;
5256         ConfigFile *cf = c->private;
5257         char *ptr;
5258         struct berval bv;
5259
5260         for (; cf; cf=cf->c_sibs, c->depth++) {
5261                 if ( !cf->c_at_head && !cf->c_cr_head && !cf->c_oc_head &&
5262                         !cf->c_om_head ) continue;
5263                 c->value_dn.bv_val = c->log;
5264                 LUTIL_SLASHPATH( cf->c_file.bv_val );
5265                 bv.bv_val = strrchr(cf->c_file.bv_val, LDAP_DIRSEP[0]);
5266                 if ( !bv.bv_val ) {
5267                         bv = cf->c_file;
5268                 } else {
5269                         bv.bv_val++;
5270                         bv.bv_len = cf->c_file.bv_len - (bv.bv_val - cf->c_file.bv_val);
5271                 }
5272                 ptr = strchr( bv.bv_val, '.' );
5273                 if ( ptr )
5274                         bv.bv_len = ptr - bv.bv_val;
5275                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=" SLAP_X_ORDERED_FMT, c->depth);
5276                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5277                         /* FIXME: how can indicate error? */
5278                         return -1;
5279                 }
5280                 strncpy( c->value_dn.bv_val + c->value_dn.bv_len, bv.bv_val,
5281                         bv.bv_len );
5282                 c->value_dn.bv_len += bv.bv_len;
5283                 c->value_dn.bv_val[c->value_dn.bv_len] ='\0';
5284
5285                 c->private = cf;
5286                 e = config_build_entry( op, rs, ceparent, c, &c->value_dn,
5287                         &CFOC_SCHEMA, NULL );
5288                 if ( !e ) {
5289                         return -1;
5290                 } else if ( e && cf->c_kids ) {
5291                         c->private = cf->c_kids;
5292                         config_build_schema_inc( c, e->e_private, op, rs );
5293                 }
5294         }
5295         return 0;
5296 }
5297
5298 #ifdef SLAPD_MODULES
5299
5300 static int
5301 config_build_modules( ConfigArgs *c, CfEntryInfo *ceparent,
5302         Operation *op, SlapReply *rs )
5303 {
5304         int i;
5305         ModPaths *mp;
5306
5307         for (i=0, mp=&modpaths; mp; mp=mp->mp_next, i++) {
5308                 if ( BER_BVISNULL( &mp->mp_path ) && !mp->mp_loads )
5309                         continue;
5310                 c->value_dn.bv_val = c->log;
5311                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=module" SLAP_X_ORDERED_FMT, i);
5312                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5313                         /* FIXME: how can indicate error? */
5314                         return -1;
5315                 }
5316                 c->private = mp;
5317                 if ( ! config_build_entry( op, rs, ceparent, c, &c->value_dn, &CFOC_MODULE, NULL )) {
5318                         return -1;
5319                 }
5320         }
5321         return 0;
5322 }
5323 #endif
5324
5325 static int
5326 config_check_schema(Operation *op, CfBackInfo *cfb)
5327 {
5328         struct berval schema_dn = BER_BVC(SCHEMA_RDN "," CONFIG_RDN);
5329         ConfigArgs c = {0};
5330         CfEntryInfo *ce, *last;
5331         Entry *e;
5332
5333         /* If there's no root entry, we must be in the midst of converting */
5334         if ( !cfb->cb_root )
5335                 return 0;
5336
5337         /* Make sure the main schema entry exists */
5338         ce = config_find_base( cfb->cb_root, &schema_dn, &last );
5339         if ( ce ) {
5340                 Attribute *a;
5341                 struct berval *bv;
5342
5343                 e = ce->ce_entry;
5344
5345                 /* Make sure it's up to date */
5346                 if ( cf_om_tail != om_sys_tail ) {
5347                         a = attr_find( e->e_attrs, cfAd_om );
5348                         if ( a ) {
5349                                 if ( a->a_nvals != a->a_vals )
5350                                         ber_bvarray_free( a->a_nvals );
5351                                 ber_bvarray_free( a->a_vals );
5352                                 a->a_vals = NULL;
5353                                 a->a_nvals = NULL;
5354                         }
5355                         oidm_unparse( &bv, NULL, NULL, 1 );
5356                         attr_merge_normalize( e, cfAd_om, bv, NULL );
5357                         ber_bvarray_free( bv );
5358                         cf_om_tail = om_sys_tail;
5359                 }
5360                 if ( cf_at_tail != at_sys_tail ) {
5361                         a = attr_find( e->e_attrs, cfAd_attr );
5362                         if ( a ) {
5363                                 if ( a->a_nvals != a->a_vals )
5364                                         ber_bvarray_free( a->a_nvals );
5365                                 ber_bvarray_free( a->a_vals );
5366                                 a->a_vals = NULL;
5367                                 a->a_nvals = NULL;
5368                         }
5369                         at_unparse( &bv, NULL, NULL, 1 );
5370                         attr_merge_normalize( e, cfAd_attr, bv, NULL );
5371                         ber_bvarray_free( bv );
5372                         cf_at_tail = at_sys_tail;
5373                 }
5374                 if ( cf_oc_tail != oc_sys_tail ) {
5375                         a = attr_find( e->e_attrs, cfAd_oc );
5376                         if ( a ) {
5377                                 if ( a->a_nvals != a->a_vals )
5378                                         ber_bvarray_free( a->a_nvals );
5379                                 ber_bvarray_free( a->a_vals );
5380                                 a->a_vals = NULL;
5381                                 a->a_nvals = NULL;
5382                         }
5383                         oc_unparse( &bv, NULL, NULL, 1 );
5384                         attr_merge_normalize( e, cfAd_oc, bv, NULL );
5385                         ber_bvarray_free( bv );
5386                         cf_oc_tail = oc_sys_tail;
5387                 }
5388         } else {
5389                 SlapReply rs = {REP_RESULT};
5390                 c.private = NULL;
5391                 e = config_build_entry( op, &rs, cfb->cb_root, &c, &schema_rdn,
5392                         &CFOC_SCHEMA, NULL );
5393                 if ( !e ) {
5394                         return -1;
5395                 }
5396                 ce = e->e_private;
5397                 ce->ce_private = cfb->cb_config;
5398                 cf_at_tail = at_sys_tail;
5399                 cf_oc_tail = oc_sys_tail;
5400                 cf_om_tail = om_sys_tail;
5401         }
5402         return 0;
5403 }
5404
5405 static const char *defacl[] = {
5406         NULL, "to", "*", "by", "*", "none", NULL
5407 };
5408
5409 static int
5410 config_back_db_open( BackendDB *be, ConfigReply *cr )
5411 {
5412         CfBackInfo *cfb = be->be_private;
5413         struct berval rdn;
5414         Entry *e, *parent;
5415         CfEntryInfo *ce, *ceparent;
5416         int i, unsupp = 0;
5417         BackendInfo *bi;
5418         ConfigArgs c;
5419         Connection conn = {0};
5420         OperationBuffer opbuf;
5421         Operation *op;
5422         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
5423         SlapReply rs = {REP_RESULT};
5424         void *thrctx = NULL;
5425
5426         Debug( LDAP_DEBUG_TRACE, "config_back_db_open\n", 0, 0, 0);
5427
5428         /* If we have no explicitly configured ACLs, don't just use
5429          * the global ACLs. Explicitly deny access to everything.
5430          */
5431         if ( frontendDB->be_acl && be->be_acl == frontendDB->be_acl ) {
5432                 parse_acl(be, "config_back_db_open", 0, 6, (char **)defacl, 0 );
5433         }
5434
5435         thrctx = ldap_pvt_thread_pool_context();
5436         connection_fake_init( &conn, &opbuf, thrctx );
5437         op = &opbuf.ob_op;
5438
5439         op->o_tag = LDAP_REQ_ADD;
5440         op->o_callback = &cb;
5441         op->o_bd = &cfb->cb_db;
5442         op->o_dn = op->o_bd->be_rootdn;
5443         op->o_ndn = op->o_bd->be_rootndn;
5444
5445         if ( !cfb->cb_use_ldif ) {
5446                 op->o_noop = 1;
5447         }
5448
5449         /* If we read the config from back-ldif, do some quick sanity checks */
5450         if ( cfb->cb_got_ldif ) {
5451                 return config_check_schema( op, cfb );
5452         }
5453
5454         /* create root of tree */
5455         rdn = config_rdn;
5456         c.private = cfb->cb_config;
5457         c.be = frontendDB;
5458         e = config_build_entry( op, &rs, NULL, &c, &rdn, &CFOC_GLOBAL, NULL );
5459         if ( !e ) {
5460                 return -1;
5461         }
5462         ce = e->e_private;
5463         cfb->cb_root = ce;
5464
5465         parent = e;
5466         ceparent = ce;
5467
5468 #ifdef SLAPD_MODULES
5469         /* Create Module nodes... */
5470         if ( modpaths.mp_loads ) {
5471                 if ( config_build_modules( &c, ceparent, op, &rs ) ){
5472                         return -1;
5473                 }
5474         }
5475 #endif
5476
5477         /* Create schema nodes... cn=schema will contain the hardcoded core
5478          * schema, read-only. Child objects will contain runtime loaded schema
5479          * files.
5480          */
5481         rdn = schema_rdn;
5482         c.private = NULL;
5483         e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_SCHEMA, NULL );
5484         if ( !e ) {
5485                 return -1;
5486         }
5487         ce = e->e_private;
5488         ce->ce_private = cfb->cb_config;
5489         cf_at_tail = at_sys_tail;
5490         cf_oc_tail = oc_sys_tail;
5491         cf_om_tail = om_sys_tail;
5492
5493         /* Create schema nodes for included schema... */
5494         if ( cfb->cb_config->c_kids ) {
5495                 c.depth = 0;
5496                 c.private = cfb->cb_config->c_kids;
5497                 if (config_build_schema_inc( &c, ce, op, &rs )) {
5498                         return -1;
5499                 }
5500         }
5501
5502         /* Create backend nodes. Skip if they don't provide a cf_table.
5503          * There usually aren't any of these.
5504          */
5505         
5506         c.line = 0;
5507         LDAP_STAILQ_FOREACH( bi, &backendInfo, bi_next) {
5508                 if (!bi->bi_cf_ocs) {
5509                         /* If it only supports the old config mech, complain. */
5510                         if ( bi->bi_config ) {
5511                                 Debug( LDAP_DEBUG_ANY,
5512                                         "WARNING: No dynamic config support for backend %s.\n",
5513                                         bi->bi_type, 0, 0 );
5514                                 unsupp++;
5515                         }
5516                         continue;
5517                 }
5518                 if (!bi->bi_private) continue;
5519
5520                 rdn.bv_val = c.log;
5521                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5522                         "%s=%s", cfAd_backend->ad_cname.bv_val, bi->bi_type);
5523                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5524                         /* FIXME: holler ... */ ;
5525                 }
5526                 c.bi = bi;
5527                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_BACKEND,
5528                         bi->bi_cf_ocs );
5529                 if ( !e ) {
5530                         return -1;
5531                 }
5532         }
5533
5534         /* Create database nodes... */
5535         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
5536         LDAP_STAILQ_NEXT(frontendDB, be_next) = LDAP_STAILQ_FIRST(&backendDB);
5537         for ( i = -1, be = frontendDB ; be;
5538                 i++, be = LDAP_STAILQ_NEXT( be, be_next )) {
5539                 slap_overinfo *oi = NULL;
5540
5541                 if ( overlay_is_over( be )) {
5542                         oi = be->bd_info->bi_private;
5543                         bi = oi->oi_orig;
5544                 } else {
5545                         bi = be->bd_info;
5546                 }
5547
5548                 /* If this backend supports the old config mechanism, but not
5549                  * the new mech, complain.
5550                  */
5551                 if ( !be->be_cf_ocs && bi->bi_db_config ) {
5552                         Debug( LDAP_DEBUG_ANY,
5553                                 "WARNING: No dynamic config support for database %s.\n",
5554                                 bi->bi_type, 0, 0 );
5555                         unsupp++;
5556                 }
5557                 rdn.bv_val = c.log;
5558                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5559                         "%s=" SLAP_X_ORDERED_FMT "%s", cfAd_database->ad_cname.bv_val,
5560                         i, bi->bi_type);
5561                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5562                         /* FIXME: holler ... */ ;
5563                 }
5564                 c.be = be;
5565                 c.bi = bi;
5566                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_DATABASE,
5567                         be->be_cf_ocs );
5568                 if ( !e ) {
5569                         return -1;
5570                 }
5571                 ce = e->e_private;
5572                 if ( be->be_cf_ocs && be->be_cf_ocs->co_cfadd )
5573                         be->be_cf_ocs->co_cfadd( op, &rs, e, &c );
5574                 /* Iterate through overlays */
5575                 if ( oi ) {
5576                         slap_overinst *on;
5577                         Entry *oe;
5578                         int j;
5579
5580                         for (j=0,on=oi->oi_list; on; j++,on=on->on_next) {
5581                                 if ( on->on_bi.bi_db_config && !on->on_bi.bi_cf_ocs ) {
5582                                         Debug( LDAP_DEBUG_ANY,
5583                                                 "WARNING: No dynamic config support for overlay %s.\n",
5584                                                 on->on_bi.bi_type, 0, 0 );
5585                                         unsupp++;
5586                                 }
5587                                 rdn.bv_val = c.log;
5588                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5589                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5590                                         cfAd_overlay->ad_cname.bv_val, j, on->on_bi.bi_type );
5591                                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5592                                         /* FIXME: holler ... */ ;
5593                                 }
5594                                 c.be = be;
5595                                 c.bi = &on->on_bi;
5596                                 oe = config_build_entry( op, &rs, ce, &c, &rdn,
5597                                         &CFOC_OVERLAY, c.bi->bi_cf_ocs );
5598                                 if ( !oe ) {
5599                                         return -1;
5600                                 }
5601                                 if ( c.bi->bi_cf_ocs && c.bi->bi_cf_ocs->co_cfadd )
5602                                         c.bi->bi_cf_ocs->co_cfadd( op, &rs, oe, &c );
5603                         }
5604                 }
5605         }
5606         if ( thrctx )
5607                 ldap_pvt_thread_pool_context_reset( thrctx );
5608
5609         if ( unsupp  && cfb->cb_use_ldif ) {
5610                 Debug( LDAP_DEBUG_ANY, "\nWARNING: The converted cn=config "
5611                         "directory is incomplete and may not work.\n\n", 0, 0, 0 );
5612         }
5613
5614         return 0;
5615 }
5616
5617 static void
5618 cfb_free_cffile( ConfigFile *cf )
5619 {
5620         ConfigFile *next;
5621
5622         for (; cf; cf=next) {
5623                 next = cf->c_sibs;
5624                 if ( cf->c_kids )
5625                         cfb_free_cffile( cf->c_kids );
5626                 ch_free( cf->c_file.bv_val );
5627                 ber_bvarray_free( cf->c_dseFiles );
5628                 ch_free( cf );
5629         }
5630 }
5631
5632 static void
5633 cfb_free_entries( CfEntryInfo *ce )
5634 {
5635         CfEntryInfo *next;
5636
5637         for (; ce; ce=next) {
5638                 next = ce->ce_sibs;
5639                 if ( ce->ce_kids )
5640                         cfb_free_entries( ce->ce_kids );
5641                 ce->ce_entry->e_private = NULL;
5642                 entry_free( ce->ce_entry );
5643                 ch_free( ce );
5644         }
5645 }
5646
5647 static int
5648 config_back_db_close( BackendDB *be, ConfigReply *cr )
5649 {
5650         CfBackInfo *cfb = be->be_private;
5651
5652         cfb_free_entries( cfb->cb_root );
5653         cfb->cb_root = NULL;
5654
5655         if ( cfb->cb_db.bd_info ) {
5656                 backend_shutdown( &cfb->cb_db );
5657         }
5658
5659         return 0;
5660 }
5661
5662 static int
5663 config_back_db_destroy( BackendDB *be, ConfigReply *cr )
5664 {
5665         CfBackInfo *cfb = be->be_private;
5666
5667         cfb_free_cffile( cfb->cb_config );
5668
5669         ch_free( cfdir.bv_val );
5670
5671         avl_free( CfOcTree, NULL );
5672
5673         if ( cfb->cb_db.bd_info ) {
5674                 cfb->cb_db.be_suffix = NULL;
5675                 cfb->cb_db.be_nsuffix = NULL;
5676                 BER_BVZERO( &cfb->cb_db.be_rootdn );
5677                 BER_BVZERO( &cfb->cb_db.be_rootndn );
5678
5679                 backend_destroy_one( &cfb->cb_db, 0 );
5680         }
5681
5682         loglevel_destroy();
5683
5684         return 0;
5685 }
5686
5687 static int
5688 config_back_db_init( BackendDB *be, ConfigReply* cr )
5689 {
5690         struct berval dn;
5691         CfBackInfo *cfb;
5692
5693         cfb = &cfBackInfo;
5694         cfb->cb_config = ch_calloc( 1, sizeof(ConfigFile));
5695         cfn = cfb->cb_config;
5696         be->be_private = cfb;
5697
5698         ber_dupbv( &be->be_rootdn, &config_rdn );
5699         ber_dupbv( &be->be_rootndn, &be->be_rootdn );
5700         ber_dupbv( &dn, &be->be_rootdn );
5701         ber_bvarray_add( &be->be_suffix, &dn );
5702         ber_dupbv( &dn, &be->be_rootdn );
5703         ber_bvarray_add( &be->be_nsuffix, &dn );
5704
5705         /* Hide from namingContexts */
5706         SLAP_BFLAGS(be) |= SLAP_BFLAG_CONFIG;
5707
5708         return 0;
5709 }
5710
5711 static int
5712 config_back_destroy( BackendInfo *bi )
5713 {
5714         ldif_must_b64_encode_release();
5715         return 0;
5716 }
5717
5718 static int
5719 config_tool_entry_open( BackendDB *be, int mode )
5720 {
5721         CfBackInfo *cfb = be->be_private;
5722         BackendInfo *bi = cfb->cb_db.bd_info;
5723
5724         if ( bi && bi->bi_tool_entry_open )
5725                 return bi->bi_tool_entry_open( &cfb->cb_db, mode );
5726         else
5727                 return -1;
5728         
5729 }
5730
5731 static int
5732 config_tool_entry_close( BackendDB *be )
5733 {
5734         CfBackInfo *cfb = be->be_private;
5735         BackendInfo *bi = cfb->cb_db.bd_info;
5736
5737         if ( bi && bi->bi_tool_entry_close )
5738                 return bi->bi_tool_entry_close( &cfb->cb_db );
5739         else
5740                 return -1;
5741 }
5742
5743 static ID
5744 config_tool_entry_first( BackendDB *be )
5745 {
5746         CfBackInfo *cfb = be->be_private;
5747         BackendInfo *bi = cfb->cb_db.bd_info;
5748
5749         if ( bi && bi->bi_tool_entry_first )
5750                 return bi->bi_tool_entry_first( &cfb->cb_db );
5751         else
5752                 return NOID;
5753 }
5754
5755 static ID
5756 config_tool_entry_next( BackendDB *be )
5757 {
5758         CfBackInfo *cfb = be->be_private;
5759         BackendInfo *bi = cfb->cb_db.bd_info;
5760
5761         if ( bi && bi->bi_tool_entry_next )
5762                 return bi->bi_tool_entry_next( &cfb->cb_db );
5763         else
5764                 return NOID;
5765 }
5766
5767 static Entry *
5768 config_tool_entry_get( BackendDB *be, ID id )
5769 {
5770         CfBackInfo *cfb = be->be_private;
5771         BackendInfo *bi = cfb->cb_db.bd_info;
5772
5773         if ( bi && bi->bi_tool_entry_get )
5774                 return bi->bi_tool_entry_get( &cfb->cb_db, id );
5775         else
5776                 return NULL;
5777 }
5778
5779 static int entry_put_got_frontend=0;
5780 static int entry_put_got_config=0;
5781 static ID
5782 config_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
5783 {
5784         CfBackInfo *cfb = be->be_private;
5785         BackendInfo *bi = cfb->cb_db.bd_info;
5786         int rc;
5787         struct berval rdn, vals[ 2 ];
5788         ConfigArgs ca;
5789         OperationBuffer opbuf;
5790         Entry *ce;
5791         Connection conn = {0};
5792         Operation *op = NULL;
5793         void *thrctx;
5794
5795         /* Create entry for frontend database if it does not exist already */
5796         if ( !entry_put_got_frontend ) {
5797                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase", 
5798                                 STRLENOF( "olcDatabase" ))) {
5799                         if ( strncmp( e->e_nname.bv_val + 
5800                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
5801                                         STRLENOF( "={-1}frontend" )) && 
5802                                         strncmp( e->e_nname.bv_val + 
5803                                         STRLENOF( "olcDatabase" ), "=frontend",
5804                                         STRLENOF( "=frontend" ))) {
5805                                 vals[1].bv_len = 0;
5806                                 vals[1].bv_val = NULL;
5807                                 memset( &ca, 0, sizeof(ConfigArgs));
5808                                 ca.be = frontendDB;
5809                                 ca.bi = frontendDB->bd_info;
5810                                 ca.be->be_cf_ocs = &CFOC_FRONTEND;
5811                                 rdn.bv_val = ca.log;
5812                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5813                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5814                                         cfAd_database->ad_cname.bv_val, -1,
5815                                         ca.bi->bi_type);
5816                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn,
5817                                                 &CFOC_DATABASE, ca.be->be_cf_ocs );
5818                                 thrctx = ldap_pvt_thread_pool_context();
5819                                 connection_fake_init2( &conn, &opbuf, thrctx,0 );
5820                                 op = &opbuf.ob_op;
5821                                 op->o_bd = &cfb->cb_db;
5822                                 op->o_tag = LDAP_REQ_ADD;
5823                                 op->ora_e = ce;
5824                                 op->o_dn = be->be_rootdn;
5825                                 op->o_ndn = be->be_rootndn;
5826                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5827                                 if ( rc != LDAP_SUCCESS ) {
5828                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5829                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5830                                         return NOID;
5831                                 }
5832
5833                                 if ( ce && bi && bi->bi_tool_entry_put && 
5834                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5835                                         entry_put_got_frontend++;
5836                                 } else {
5837                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5838                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5839                                         return NOID;
5840                                 }
5841                         } else {
5842                                 entry_put_got_frontend++;
5843                         }
5844                 }
5845         }
5846         /* Create entry for config database if it does not exist already */
5847         if ( !entry_put_got_config ) {
5848                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase",
5849                                 STRLENOF( "olcDatabase" ))) {
5850                         if ( strncmp( e->e_nname.bv_val +
5851                                         STRLENOF( "olcDatabase" ), "={0}config",
5852                                         STRLENOF( "={0}config" )) &&
5853                                         strncmp( e->e_nname.bv_val +
5854                                         STRLENOF( "olcDatabase" ), "=config",
5855                                         STRLENOF( "=config" )) ) {
5856                                 vals[1].bv_len = 0;
5857                                 vals[1].bv_val = NULL;
5858                                 memset( &ca, 0, sizeof(ConfigArgs));
5859                                 ca.be = LDAP_STAILQ_FIRST( &backendDB );
5860                                 ca.bi = ca.be->bd_info;
5861                                 rdn.bv_val = ca.log;
5862                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5863                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5864                                         cfAd_database->ad_cname.bv_val, 0,
5865                                         ca.bi->bi_type);
5866                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn, &CFOC_DATABASE,
5867                                                 ca.be->be_cf_ocs );
5868                                 if ( ! op ) {
5869                                         thrctx = ldap_pvt_thread_pool_context();
5870                                         connection_fake_init2( &conn, &opbuf, thrctx,0 );
5871                                         op = &opbuf.ob_op;
5872                                         op->o_bd = &cfb->cb_db;
5873                                         op->o_tag = LDAP_REQ_ADD;
5874                                         op->o_dn = be->be_rootdn;
5875                                         op->o_ndn = be->be_rootndn;
5876                                 }
5877                                 op->ora_e = ce;
5878                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5879                                 if ( rc != LDAP_SUCCESS ) {
5880                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5881                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5882                                         return NOID;
5883                                 }
5884                                 if (ce && bi && bi->bi_tool_entry_put &&
5885                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5886                                         entry_put_got_config++;
5887                                 } else {
5888                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5889                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5890                                         return NOID;
5891                                 }
5892                         } else {
5893                                 entry_put_got_config++;
5894                         }
5895                 }
5896         }
5897         if ( bi && bi->bi_tool_entry_put &&
5898                 config_add_internal( cfb, e, &ca, NULL, NULL, NULL ) == 0 )
5899                 return bi->bi_tool_entry_put( &cfb->cb_db, e, text );
5900         else
5901                 return NOID;
5902 }
5903
5904 static struct {
5905         char *name;
5906         AttributeDescription **desc;
5907 } ads[] = {
5908         { "attribute", &cfAd_attr },
5909         { "backend", &cfAd_backend },
5910         { "database", &cfAd_database },
5911         { "include", &cfAd_include },
5912         { "objectclass", &cfAd_oc },
5913         { "objectidentifier", &cfAd_om },
5914         { "overlay", &cfAd_overlay },
5915         { NULL, NULL }
5916 };
5917
5918 /* Notes:
5919  *   add / delete: all types that may be added or deleted must use an
5920  * X-ORDERED attributeType for their RDN. Adding and deleting entries
5921  * should automatically renumber the index of any siblings as needed,
5922  * so that no gaps in the numbering sequence exist after the add/delete
5923  * is completed.
5924  *   What can be added:
5925  *     schema objects
5926  *     backend objects for backend-specific config directives
5927  *     database objects
5928  *     overlay objects
5929  *
5930  *   delete: probably no support this time around.
5931  *
5932  *   modrdn: generally not done. Will be invoked automatically by add/
5933  * delete to update numbering sequence. Perform as an explicit operation
5934  * so that the renumbering effect may be replicated. Subtree rename must
5935  * be supported, since renumbering a database will affect all its child
5936  * overlays.
5937  *
5938  *  modify: must be fully supported. 
5939  */
5940
5941 int
5942 config_back_initialize( BackendInfo *bi )
5943 {
5944         ConfigTable             *ct = config_back_cf_table;
5945         ConfigArgs ca;
5946         char                    *argv[4];
5947         int                     i;
5948         AttributeDescription    *ad = NULL;
5949         const char              *text;
5950         static char             *controls[] = {
5951                 LDAP_CONTROL_MANAGEDSAIT,
5952                 NULL
5953         };
5954
5955         /* Make sure we don't exceed the bits reserved for userland */
5956         config_check_userland( CFG_LAST );
5957
5958         bi->bi_controls = controls;
5959
5960         bi->bi_open = 0;
5961         bi->bi_close = 0;
5962         bi->bi_config = 0;
5963         bi->bi_destroy = config_back_destroy;
5964
5965         bi->bi_db_init = config_back_db_init;
5966         bi->bi_db_config = 0;
5967         bi->bi_db_open = config_back_db_open;
5968         bi->bi_db_close = config_back_db_close;
5969         bi->bi_db_destroy = config_back_db_destroy;
5970
5971         bi->bi_op_bind = config_back_bind;
5972         bi->bi_op_unbind = 0;
5973         bi->bi_op_search = config_back_search;
5974         bi->bi_op_compare = 0;
5975         bi->bi_op_modify = config_back_modify;
5976         bi->bi_op_modrdn = config_back_modrdn;
5977         bi->bi_op_add = config_back_add;
5978         bi->bi_op_delete = config_back_delete;
5979         bi->bi_op_abandon = 0;
5980
5981         bi->bi_extended = 0;
5982
5983         bi->bi_chk_referrals = 0;
5984
5985         bi->bi_access_allowed = slap_access_allowed;
5986
5987         bi->bi_connection_init = 0;
5988         bi->bi_connection_destroy = 0;
5989
5990         bi->bi_entry_release_rw = config_entry_release;
5991         bi->bi_entry_get_rw = config_back_entry_get;
5992
5993         bi->bi_tool_entry_open = config_tool_entry_open;
5994         bi->bi_tool_entry_close = config_tool_entry_close;
5995         bi->bi_tool_entry_first = config_tool_entry_first;
5996         bi->bi_tool_entry_next = config_tool_entry_next;
5997         bi->bi_tool_entry_get = config_tool_entry_get;
5998         bi->bi_tool_entry_put = config_tool_entry_put;
5999
6000         ca.argv = argv;
6001         argv[ 0 ] = "slapd";
6002         ca.argv = argv;
6003         ca.argc = 3;
6004         ca.fname = argv[0];
6005
6006         argv[3] = NULL;
6007         for (i=0; OidMacros[i].name; i++ ) {
6008                 argv[1] = OidMacros[i].name;
6009                 argv[2] = OidMacros[i].oid;
6010                 parse_oidm( &ca, 0, NULL );
6011         }
6012
6013         bi->bi_cf_ocs = cf_ocs;
6014
6015         i = config_register_schema( ct, cf_ocs );
6016         if ( i ) return i;
6017
6018         /* setup olcRootPW to be base64-encoded when written in LDIF form;
6019          * basically, we don't care if it fails */
6020         i = slap_str2ad( "olcRootPW", &ad, &text );
6021         if ( i ) {
6022                 Debug( LDAP_DEBUG_ANY, "config_back_initialize: "
6023                         "warning, unable to get \"olcRootPW\" "
6024                         "attribute description: %d: %s\n",
6025                         i, text, 0 );
6026         } else {
6027                 (void)ldif_must_b64_encode_register( ad->ad_cname.bv_val,
6028                         ad->ad_type->sat_oid );
6029         }
6030
6031         /* set up the notable AttributeDescriptions */
6032         i = 0;
6033         for (;ct->name;ct++) {
6034                 if (strcmp(ct->name, ads[i].name)) continue;
6035                 *ads[i].desc = ct->ad;
6036                 i++;
6037                 if (!ads[i].name) break;
6038         }
6039
6040         return 0;
6041 }
6042