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