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