]> git.sur5r.net Git - openldap/blob - servers/slapd/bconfig.c
don't let back-monitor appear __after__ a database that hides it; currently, only...
[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 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 static struct berval config_rdn = BER_BVC("cn=config");
41 static struct berval schema_rdn = BER_BVC("cn=schema");
42
43 #define IFMT    "{%d}"
44
45 #ifdef SLAPD_MODULES
46 typedef struct modpath_s {
47         struct modpath_s *mp_next;
48         struct berval mp_path;
49         BerVarray mp_loads;
50 } ModPaths;
51
52 static ModPaths modpaths, *modlast = &modpaths, *modcur = &modpaths;
53 #endif
54
55 typedef struct ConfigFile {
56         struct ConfigFile *c_sibs;
57         struct ConfigFile *c_kids;
58         struct berval c_file;
59         AttributeType *c_at_head, *c_at_tail;
60         ContentRule *c_cr_head, *c_cr_tail;
61         ObjectClass *c_oc_head, *c_oc_tail;
62         OidMacro *c_om_head, *c_om_tail;
63         BerVarray c_dseFiles;
64 } ConfigFile;
65
66 typedef struct {
67         ConfigFile *cb_config;
68         CfEntryInfo *cb_root;
69         BackendDB       cb_db;  /* underlying database */
70         int             cb_got_ldif;
71         int             cb_use_ldif;
72 } CfBackInfo;
73
74 /* These do nothing in slapd, they're kept only to make them
75  * editable here.
76  */
77 static char *replica_pidFile, *replica_argsFile;
78 static int replicationInterval;
79
80 static char     *passwd_salt;
81 static char     *logfileName;
82 #ifdef SLAP_AUTH_REWRITE
83 static BerVarray authz_rewrites;
84 #endif
85
86 static struct berval cfdir;
87
88 /* Private state */
89 static AttributeDescription *cfAd_backend, *cfAd_database, *cfAd_overlay,
90         *cfAd_include;
91
92 static ConfigFile *cfn;
93
94 static Avlnode *CfOcTree;
95
96 static int config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca,
97         SlapReply *rs, int *renumber );
98
99 static ConfigDriver config_fname;
100 static ConfigDriver config_cfdir;
101 static ConfigDriver config_generic;
102 static ConfigDriver config_search_base;
103 static ConfigDriver config_passwd_hash;
104 static ConfigDriver config_schema_dn;
105 static ConfigDriver config_sizelimit;
106 static ConfigDriver config_timelimit;
107 static ConfigDriver config_overlay;
108 static ConfigDriver config_suffix; 
109 static ConfigDriver config_rootdn;
110 static ConfigDriver config_rootpw;
111 static ConfigDriver config_restrict;
112 static ConfigDriver config_allows;
113 static ConfigDriver config_disallows;
114 static ConfigDriver config_requires;
115 static ConfigDriver config_security;
116 static ConfigDriver config_referral;
117 static ConfigDriver config_loglevel;
118 static ConfigDriver config_replica;
119 static ConfigDriver config_updatedn;
120 static ConfigDriver config_updateref;
121 static ConfigDriver config_include;
122 #ifdef HAVE_TLS
123 static ConfigDriver config_tls_option;
124 static ConfigDriver config_tls_config;
125 #endif
126 extern ConfigDriver syncrepl_config;
127
128 enum {
129         CFG_ACL = 1,
130         CFG_BACKEND,
131         CFG_DATABASE,
132         CFG_TLS_RAND,
133         CFG_TLS_CIPHER,
134         CFG_TLS_CERT_FILE,
135         CFG_TLS_CERT_KEY,
136         CFG_TLS_CA_PATH,
137         CFG_TLS_CA_FILE,
138         CFG_TLS_VERIFY,
139         CFG_TLS_CRLCHECK,
140         CFG_CONCUR,
141         CFG_THREADS,
142         CFG_SALT,
143         CFG_LIMITS,
144         CFG_RO,
145         CFG_REWRITE,
146         CFG_DEPTH,
147         CFG_OID,
148         CFG_OC,
149         CFG_DIT,
150         CFG_ATTR,
151         CFG_ATOPT,
152         CFG_REPLOG,
153         CFG_ROOTDSE,
154         CFG_LOGFILE,
155         CFG_PLUGIN,
156         CFG_MODLOAD,
157         CFG_MODPATH,
158         CFG_LASTMOD,
159         CFG_AZPOLICY,
160         CFG_AZREGEXP,
161         CFG_SASLSECP,
162         CFG_SSTR_IF_MAX,
163         CFG_SSTR_IF_MIN,
164
165         CFG_LAST
166 };
167
168 typedef struct {
169         char *name, *oid;
170 } OidRec;
171
172 static OidRec OidMacros[] = {
173         /* OpenLDAProot:666.11.1 */
174         { "OLcfg", "1.3.6.1.4.1.4203.666.11.1" },
175         { "OLcfgAt", "OLcfg:3" },
176         { "OLcfgGlAt", "OLcfgAt:0" },
177         { "OLcfgBkAt", "OLcfgAt:1" },
178         { "OLcfgDbAt", "OLcfgAt:2" },
179         { "OLcfgOvAt", "OLcfgAt:3" },
180         { "OLcfgOc", "OLcfg:4" },
181         { "OLcfgGlOc", "OLcfgOc:0" },
182         { "OLcfgBkOc", "OLcfgOc:1" },
183         { "OLcfgDbOc", "OLcfgOc:2" },
184         { "OLcfgOvOc", "OLcfgOc:3" },
185         { "OMsyn", "1.3.6.1.4.1.1466.115.121.1" },
186         { "OMsInteger", "OMsyn:27" },
187         { "OMsBoolean", "OMsyn:7" },
188         { "OMsDN", "OMsyn:12" },
189         { "OMsDirectoryString", "OMsyn:15" },
190         { "OMsOctetString", "OMsyn:40" },
191         { NULL, NULL }
192 };
193
194 /*
195  * OLcfg{Bk|Db}{Oc|At}:0                -> common
196  * OLcfg{Bk|Db}{Oc|At}:1                -> bdb
197  * OLcfg{Bk|Db}{Oc|At}:2                -> ldif
198  * OLcfg{Bk|Db}{Oc|At}:3                -> ldap?
199  */
200
201 /* alphabetical ordering */
202
203 static ConfigTable config_back_cf_table[] = {
204         /* This attr is read-only */
205         { "", "", 0, 0, 0, ARG_MAGIC,
206                 &config_fname, "( OLcfgGlAt:78 NAME 'olcConfigFile' "
207                         "DESC 'File for slapd configuration directives' "
208                         "EQUALITY caseIgnoreMatch "
209                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
210         { "", "", 0, 0, 0, ARG_MAGIC,
211                 &config_cfdir, "( OLcfgGlAt:79 NAME 'olcConfigDir' "
212                         "DESC 'Directory for slapd configuration backend' "
213                         "EQUALITY caseIgnoreMatch "
214                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
215         { "access",     NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC|CFG_ACL,
216                 &config_generic, "( OLcfgGlAt:1 NAME 'olcAccess' "
217                         "DESC 'Access Control List' "
218                         "EQUALITY caseIgnoreMatch "
219                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
220         { "allows",     "features", 2, 0, 5, ARG_PRE_DB|ARG_MAGIC,
221                 &config_allows, "( OLcfgGlAt:2 NAME 'olcAllows' "
222                         "DESC 'Allowed set of deprecated features' "
223                         "EQUALITY caseIgnoreMatch "
224                         "SYNTAX OMsDirectoryString )", NULL, NULL },
225         { "argsfile", "file", 2, 2, 0, ARG_STRING,
226                 &slapd_args_file, "( OLcfgGlAt:3 NAME 'olcArgsFile' "
227                         "DESC 'File for slapd command line options' "
228                         "EQUALITY caseIgnoreMatch "
229                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
230         { "attributeoptions", NULL, 0, 0, 0, ARG_MAGIC|CFG_ATOPT,
231                 &config_generic, "( OLcfgGlAt:5 NAME 'olcAttributeOptions' "
232                         "EQUALITY caseIgnoreMatch "
233                         "SYNTAX OMsDirectoryString )", NULL, NULL },
234         { "attribute",  "attribute", 2, 0, 9,
235                 ARG_PAREN|ARG_MAGIC|CFG_ATTR|ARG_NO_DELETE|ARG_NO_INSERT,
236                 &config_generic, "( OLcfgGlAt:4 NAME 'olcAttributeTypes' "
237                         "DESC 'OpenLDAP attributeTypes' "
238                         "EQUALITY caseIgnoreMatch "
239                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
240                                 NULL, NULL },
241         { "authid-rewrite", NULL, 2, 0, STRLENOF( "authid-rewrite" ),
242 #ifdef SLAP_AUTH_REWRITE
243                 ARG_MAGIC|CFG_REWRITE|ARG_NO_INSERT, &config_generic,
244 #else
245                 ARG_IGNORED, NULL,
246 #endif
247                  "( OLcfgGlAt:6 NAME 'olcAuthIDRewrite' "
248                         "EQUALITY caseIgnoreMatch "
249                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
250         { "authz-policy", "policy", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_AZPOLICY,
251                 &config_generic, "( OLcfgGlAt:7 NAME 'olcAuthzPolicy' "
252                         "EQUALITY caseIgnoreMatch "
253                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
254         { "authz-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP|ARG_NO_INSERT,
255                 &config_generic, "( OLcfgGlAt:8 NAME 'olcAuthzRegexp' "
256                         "EQUALITY caseIgnoreMatch "
257                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
258         { "backend", "type", 2, 2, 0, ARG_PRE_DB|ARG_MAGIC|CFG_BACKEND,
259                 &config_generic, "( OLcfgGlAt:9 NAME 'olcBackend' "
260                         "DESC 'A type of backend' "
261                         "EQUALITY caseIgnoreMatch "
262                         "SYNTAX OMsDirectoryString SINGLE-VALUE X-ORDERED 'SIBLINGS' )",
263                                 NULL, NULL },
264         { "concurrency", "level", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_CONCUR,
265                 &config_generic, "( OLcfgGlAt:10 NAME 'olcConcurrency' "
266                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
267         { "conn_max_pending", "max", 2, 2, 0, ARG_INT,
268                 &slap_conn_max_pending, "( OLcfgGlAt:11 NAME 'olcConnMaxPending' "
269                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
270         { "conn_max_pending_auth", "max", 2, 2, 0, ARG_INT,
271                 &slap_conn_max_pending_auth, "( OLcfgGlAt:12 NAME 'olcConnMaxPendingAuth' "
272                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
273         { "database", "type", 2, 2, 0, ARG_MAGIC|CFG_DATABASE,
274                 &config_generic, "( OLcfgGlAt:13 NAME 'olcDatabase' "
275                         "DESC 'The backend type for a database instance' "
276                         "SUP olcBackend SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
277         { "defaultSearchBase", "dn", 2, 2, 0, ARG_PRE_BI|ARG_PRE_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
278                 &config_search_base, "( OLcfgGlAt:14 NAME 'olcDefaultSearchBase' "
279                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
280         { "disallows", "features", 2, 0, 8, ARG_PRE_DB|ARG_MAGIC,
281                 &config_disallows, "( OLcfgGlAt:15 NAME 'olcDisallows' "
282                         "EQUALITY caseIgnoreMatch "
283                         "SYNTAX OMsDirectoryString )", NULL, NULL },
284         { "ditcontentrule",     NULL, 0, 0, 0, ARG_MAGIC|CFG_DIT|ARG_NO_DELETE|ARG_NO_INSERT,
285                 &config_generic, "( OLcfgGlAt:16 NAME 'olcDitContentRules' "
286                         "DESC 'OpenLDAP DIT content rules' "
287                         "EQUALITY caseIgnoreMatch "
288                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
289                         NULL, NULL },
290         { "gentlehup", "on|off", 2, 2, 0,
291 #ifdef SIGHUP
292                 ARG_ON_OFF, &global_gentlehup,
293 #else
294                 ARG_IGNORED, NULL,
295 #endif
296                 "( OLcfgGlAt:17 NAME 'olcGentleHUP' "
297                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
298         { "idletimeout", "timeout", 2, 2, 0, ARG_INT,
299                 &global_idletimeout, "( OLcfgGlAt:18 NAME 'olcIdleTimeout' "
300                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
301         { "include", "file", 2, 2, 0, ARG_MAGIC,
302                 &config_include, "( OLcfgGlAt:19 NAME 'olcInclude' "
303                         "SUP labeledURI )", NULL, NULL },
304         { "index_substr_if_minlen", "min", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MIN,
305                 &config_generic, "( OLcfgGlAt:20 NAME 'olcIndexSubstrIfMinLen' "
306                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
307         { "index_substr_if_maxlen", "max", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MAX,
308                 &config_generic, "( OLcfgGlAt:21 NAME 'olcIndexSubstrIfMaxLen' "
309                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
310         { "index_substr_any_len", "len", 2, 2, 0, ARG_INT|ARG_NONZERO,
311                 &index_substr_any_len, "( OLcfgGlAt:22 NAME 'olcIndexSubstrAnyLen' "
312                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
313         { "index_substr_any_step", "step", 2, 2, 0, ARG_INT|ARG_NONZERO,
314                 &index_substr_any_step, "( OLcfgGlAt:23 NAME 'olcIndexSubstrAnyStep' "
315                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
316         { "lastmod", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_LASTMOD,
317                 &config_generic, "( OLcfgDbAt:0.4 NAME 'olcLastMod' "
318                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
319         { "limits", "limits", 2, 0, 0, ARG_DB|ARG_MAGIC|CFG_LIMITS,
320                 &config_generic, "( OLcfgDbAt:0.5 NAME 'olcLimits' "
321                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
322         { "localSSF", "ssf", 2, 2, 0, ARG_INT,
323                 &local_ssf, "( OLcfgGlAt:26 NAME 'olcLocalSSF' "
324                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
325         { "logfile", "file", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_LOGFILE,
326                 &config_generic, "( OLcfgGlAt:27 NAME 'olcLogFile' "
327                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
328         { "loglevel", "level", 2, 0, 0, ARG_MAGIC,
329                 &config_loglevel, "( OLcfgGlAt:28 NAME 'olcLogLevel' "
330                         "SYNTAX OMsDirectoryString )", NULL, NULL },
331         { "maxDerefDepth", "depth", 2, 2, 0, ARG_DB|ARG_INT|ARG_MAGIC|CFG_DEPTH,
332                 &config_generic, "( OLcfgDbAt:0.6 NAME 'olcMaxDerefDepth' "
333                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
334         { "moduleload", "file", 2, 0, 0,
335 #ifdef SLAPD_MODULES
336                 ARG_MAGIC|CFG_MODLOAD, &config_generic,
337 #else
338                 ARG_IGNORED, NULL,
339 #endif
340                 "( OLcfgGlAt:30 NAME 'olcModuleLoad' "
341                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
342         { "modulepath", "path", 2, 2, 0,
343 #ifdef SLAPD_MODULES
344                 ARG_MAGIC|CFG_MODPATH|ARG_NO_DELETE|ARG_NO_INSERT, &config_generic,
345 #else
346                 ARG_IGNORED, NULL,
347 #endif
348                 "( OLcfgGlAt:31 NAME 'olcModulePath' "
349                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
350         { "objectclass", "objectclass", 2, 0, 0, ARG_PAREN|ARG_MAGIC|CFG_OC|ARG_NO_DELETE|ARG_NO_INSERT,
351                 &config_generic, "( OLcfgGlAt:32 NAME 'olcObjectClasses' "
352                 "DESC 'OpenLDAP object classes' "
353                 "EQUALITY caseIgnoreMatch "
354                 "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
355                         NULL, NULL },
356         { "objectidentifier", NULL,     0, 0, 0, ARG_MAGIC|CFG_OID,
357                 &config_generic, "( OLcfgGlAt:33 NAME 'olcObjectIdentifier' "
358                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
359         { "overlay", "overlay", 2, 2, 0, ARG_MAGIC,
360                 &config_overlay, "( OLcfgGlAt:34 NAME 'olcOverlay' "
361                         "SUP olcDatabase SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
362         { "password-crypt-salt-format", "salt", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_SALT,
363                 &config_generic, "( OLcfgGlAt:35 NAME 'olcPasswordCryptSaltFormat' "
364                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
365         { "password-hash", "hash", 2, 2, 0, ARG_MAGIC,
366                 &config_passwd_hash, "( OLcfgGlAt:36 NAME 'olcPasswordHash' "
367                         "SYNTAX OMsDirectoryString )", NULL, NULL },
368         { "pidfile", "file", 2, 2, 0, ARG_STRING,
369                 &slapd_pid_file, "( OLcfgGlAt:37 NAME 'olcPidFile' "
370                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
371         { "plugin", NULL, 0, 0, 0,
372 #ifdef LDAP_SLAPI
373                 ARG_MAGIC|CFG_PLUGIN, &config_generic,
374 #else
375                 ARG_IGNORED, NULL,
376 #endif
377                 "( OLcfgGlAt:38 NAME 'olcPlugin' "
378                         "SYNTAX OMsDirectoryString )", NULL, NULL },
379         { "pluginlog", "filename", 2, 2, 0,
380 #ifdef LDAP_SLAPI
381                 ARG_STRING, &slapi_log_file,
382 #else
383                 ARG_IGNORED, NULL,
384 #endif
385                 "( OLcfgGlAt:39 NAME 'olcPluginLogFile' "
386                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
387         { "readonly", "on|off", 2, 2, 0, ARG_MAY_DB|ARG_ON_OFF|ARG_MAGIC|CFG_RO,
388                 &config_generic, "( OLcfgGlAt:40 NAME 'olcReadOnly' "
389                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
390         { "referral", "url", 2, 2, 0, ARG_MAGIC,
391                 &config_referral, "( OLcfgGlAt:41 NAME 'olcReferral' "
392                         "SUP labeledURI SINGLE-VALUE )", NULL, NULL },
393         { "replica", "host or uri", 2, 0, 0, ARG_DB|ARG_MAGIC,
394                 &config_replica, "( OLcfgDbAt:0.7 NAME 'olcReplica' "
395                         "SUP labeledURI )", NULL, NULL },
396         { "replica-argsfile", NULL, 0, 0, 0, ARG_STRING,
397                 &replica_argsFile, "( OLcfgGlAt:43 NAME 'olcReplicaArgsFile' "
398                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
399         { "replica-pidfile", NULL, 0, 0, 0, ARG_STRING,
400                 &replica_pidFile, "( OLcfgGlAt:44 NAME 'olcReplicaPidFile' "
401                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
402         { "replicationInterval", NULL, 0, 0, 0, ARG_INT,
403                 &replicationInterval, "( OLcfgGlAt:45 NAME 'olcReplicationInterval' "
404                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
405         { "replogfile", "filename", 2, 2, 0, ARG_MAY_DB|ARG_MAGIC|ARG_STRING|CFG_REPLOG,
406                 &config_generic, "( OLcfgGlAt:46 NAME 'olcReplogFile' "
407                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
408         { "require", "features", 2, 0, 7, ARG_MAY_DB|ARG_MAGIC,
409                 &config_requires, "( OLcfgGlAt:47 NAME 'olcRequires' "
410                         "SYNTAX OMsDirectoryString )", NULL, NULL },
411         { "restrict", "op_list", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
412                 &config_restrict, "( OLcfgGlAt:48 NAME 'olcRestrict' "
413                         "SYNTAX OMsDirectoryString )", NULL, NULL },
414         { "reverse-lookup", "on|off", 2, 2, 0,
415 #ifdef SLAPD_RLOOKUPS
416                 ARG_ON_OFF, &use_reverse_lookup,
417 #else
418                 ARG_IGNORED, NULL,
419 #endif
420                 "( OLcfgGlAt:49 NAME 'olcReverseLookup' "
421                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
422         { "rootdn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
423                 &config_rootdn, "( OLcfgDbAt:0.8 NAME 'olcRootDN' "
424                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
425         { "rootDSE", "file", 2, 2, 0, ARG_MAGIC|CFG_ROOTDSE,
426                 &config_generic, "( OLcfgGlAt:51 NAME 'olcRootDSE' "
427                         "SYNTAX OMsDirectoryString )", NULL, NULL },
428         { "rootpw", "password", 2, 2, 0, ARG_BERVAL|ARG_DB|ARG_MAGIC,
429                 &config_rootpw, "( OLcfgDbAt:0.9 NAME 'olcRootPW' "
430                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
431         { "sasl-authz-policy", NULL, 2, 2, 0, ARG_MAGIC|CFG_AZPOLICY,
432                 &config_generic, NULL, NULL, NULL },
433         { "sasl-host", "host", 2, 2, 0,
434 #ifdef HAVE_CYRUS_SASL
435                 ARG_STRING|ARG_UNIQUE, &global_host,
436 #else
437                 ARG_IGNORED, NULL,
438 #endif
439                 "( OLcfgGlAt:53 NAME 'olcSaslHost' "
440                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
441         { "sasl-realm", "realm", 2, 2, 0,
442 #ifdef HAVE_CYRUS_SASL
443                 ARG_STRING|ARG_UNIQUE, &global_realm,
444 #else
445                 ARG_IGNORED, NULL,
446 #endif
447                 "( OLcfgGlAt:54 NAME 'olcSaslRealm' "
448                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
449         { "sasl-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
450                 &config_generic, NULL, NULL, NULL },
451         { "sasl-secprops", "properties", 2, 2, 0,
452 #ifdef HAVE_CYRUS_SASL
453                 ARG_MAGIC|CFG_SASLSECP, &config_generic,
454 #else
455                 ARG_IGNORED, NULL,
456 #endif
457                 "( OLcfgGlAt:56 NAME 'olcSaslSecProps' "
458                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
459         { "saslRegexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
460                 &config_generic, NULL, NULL, NULL },
461         { "schemadn", "dn", 2, 2, 0, ARG_MAY_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
462                 &config_schema_dn, "( OLcfgGlAt:58 NAME 'olcSchemaDN' "
463                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
464         { "security", "factors", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
465                 &config_security, "( OLcfgGlAt:59 NAME 'olcSecurity' "
466                         "SYNTAX OMsDirectoryString )", NULL, NULL },
467         { "sizelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
468                 &config_sizelimit, "( OLcfgGlAt:60 NAME 'olcSizeLimit' "
469                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
470         { "sockbuf_max_incoming", "max", 2, 2, 0, ARG_BER_LEN_T,
471                 &sockbuf_max_incoming, "( OLcfgGlAt:61 NAME 'olcSockbufMaxIncoming' "
472                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
473         { "sockbuf_max_incoming_auth", "max", 2, 2, 0, ARG_BER_LEN_T,
474                 &sockbuf_max_incoming_auth, "( OLcfgGlAt:62 NAME 'olcSockbufMaxIncomingAuth' "
475                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
476         { "srvtab", "file", 2, 2, 0,
477 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
478                 ARG_STRING, &ldap_srvtab,
479 #else
480                 ARG_IGNORED, NULL,
481 #endif
482                 "( OLcfgGlAt:63 NAME 'olcSrvtab' "
483                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
484         { "suffix",     "suffix", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
485                 &config_suffix, "( OLcfgDbAt:0.10 NAME 'olcSuffix' "
486                         "SYNTAX OMsDN )", NULL, NULL },
487         { "syncrepl", NULL, 0, 0, 0, ARG_DB|ARG_MAGIC,
488                 &syncrepl_config, "( OLcfgDbAt:0.11 NAME 'olcSyncrepl' "
489                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
490         { "threads", "count", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_THREADS,
491                 &config_generic, "( OLcfgGlAt:66 NAME 'olcThreads' "
492                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
493         { "timelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
494                 &config_timelimit, "( OLcfgGlAt:67 NAME 'olcTimeLimit' "
495                         "SYNTAX OMsDirectoryString )", NULL, NULL },
496         { "TLSCACertificateFile", NULL, 0, 0, 0,
497 #ifdef HAVE_TLS
498                 CFG_TLS_CA_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
499 #else
500                 ARG_IGNORED, NULL,
501 #endif
502                 "( OLcfgGlAt:68 NAME 'olcTLSCACertificateFile' "
503                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
504         { "TLSCACertificatePath", NULL, 0, 0, 0,
505 #ifdef HAVE_TLS
506                 CFG_TLS_CA_PATH|ARG_STRING|ARG_MAGIC, &config_tls_option,
507 #else
508                 ARG_IGNORED, NULL,
509 #endif
510                 "( OLcfgGlAt:69 NAME 'olcTLSCACertificatePath' "
511                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
512         { "TLSCertificateFile", NULL, 0, 0, 0,
513 #ifdef HAVE_TLS
514                 CFG_TLS_CERT_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
515 #else
516                 ARG_IGNORED, NULL,
517 #endif
518                 "( OLcfgGlAt:70 NAME 'olcTLSCertificateFile' "
519                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
520         { "TLSCertificateKeyFile", NULL, 0, 0, 0,
521 #ifdef HAVE_TLS
522                 CFG_TLS_CERT_KEY|ARG_STRING|ARG_MAGIC, &config_tls_option,
523 #else
524                 ARG_IGNORED, NULL,
525 #endif
526                 "( OLcfgGlAt:71 NAME 'olcTLSCertificateKeyFile' "
527                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
528         { "TLSCipherSuite",     NULL, 0, 0, 0,
529 #ifdef HAVE_TLS
530                 CFG_TLS_CIPHER|ARG_STRING|ARG_MAGIC, &config_tls_option,
531 #else
532                 ARG_IGNORED, NULL,
533 #endif
534                 "( OLcfgGlAt:72 NAME 'olcTLSCipherSuite' "
535                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
536         { "TLSCRLCheck", NULL, 0, 0, 0,
537 #if defined(HAVE_TLS) && defined(HAVE_OPENSSL_CRL)
538                 CFG_TLS_CRLCHECK|ARG_STRING|ARG_MAGIC, &config_tls_config,
539 #else
540                 ARG_IGNORED, NULL,
541 #endif
542                 "( OLcfgGlAt:73 NAME 'olcTLSCRLCheck' "
543                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
544         { "TLSRandFile", NULL, 0, 0, 0,
545 #ifdef HAVE_TLS
546                 CFG_TLS_RAND|ARG_STRING|ARG_MAGIC, &config_tls_option,
547 #else
548                 ARG_IGNORED, NULL,
549 #endif
550                 "( OLcfgGlAt:74 NAME 'olcTLSRandFile' "
551                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
552         { "TLSVerifyClient", NULL, 0, 0, 0,
553 #ifdef HAVE_TLS
554                 CFG_TLS_VERIFY|ARG_STRING|ARG_MAGIC, &config_tls_config,
555 #else
556                 ARG_IGNORED, NULL,
557 #endif
558                 "( OLcfgGlAt:75 NAME 'olcTLSVerifyClient' "
559                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
560         { "ucdata-path", "path", 2, 2, 0, ARG_IGNORED,
561                 NULL, NULL, NULL, NULL },
562         { "updatedn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
563                 &config_updatedn, "( OLcfgDbAt:0.12 NAME 'olcUpdateDN' "
564                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
565         { "updateref", "url", 2, 2, 0, ARG_DB|ARG_MAGIC,
566                 &config_updateref, "( OLcfgDbAt:0.13 NAME 'olcUpdateRef' "
567                         "SUP labeledURI )", NULL, NULL },
568         { NULL, NULL, 0, 0, 0, ARG_IGNORED,
569                 NULL, NULL, NULL, NULL }
570 };
571
572 /* Routines to check if a child can be added to this type */
573 static ConfigLDAPadd cfAddSchema, cfAddInclude, cfAddDatabase,
574         cfAddBackend, cfAddModule, cfAddOverlay;
575
576 /* NOTE: be careful when defining array members
577  * that can be conditionally compiled */
578 #define CFOC_GLOBAL     cf_ocs[1]
579 #define CFOC_SCHEMA     cf_ocs[2]
580 #define CFOC_BACKEND    cf_ocs[3]
581 #define CFOC_DATABASE   cf_ocs[4]
582 #define CFOC_OVERLAY    cf_ocs[5]
583 #define CFOC_INCLUDE    cf_ocs[6]
584 #define CFOC_FRONTEND   cf_ocs[7]
585 #ifdef SLAPD_MODULES
586 #define CFOC_MODULE     cf_ocs[8]
587 #endif /* SLAPD_MODULES */
588
589 static ConfigOCs cf_ocs[] = {
590         { "( OLcfgGlOc:0 "
591                 "NAME 'olcConfig' "
592                 "DESC 'OpenLDAP configuration object' "
593                 "ABSTRACT SUP top )", Cft_Abstract, NULL },
594         { "( OLcfgGlOc:1 "
595                 "NAME 'olcGlobal' "
596                 "DESC 'OpenLDAP Global configuration options' "
597                 "SUP olcConfig STRUCTURAL "
598                 "MAY ( cn $ olcConfigFile $ olcConfigDir $ olcAllows $ olcArgsFile $ "
599                  "olcAttributeOptions $ olcAuthIDRewrite $ "
600                  "olcAuthzPolicy $ olcAuthzRegexp $ olcConcurrency $ "
601                  "olcConnMaxPending $ olcConnMaxPendingAuth $ "
602                  "olcDisallows $ olcGentleHUP $ olcIdleTimeout $ "
603                  "olcIndexSubstrIfMaxLen $ olcIndexSubstrIfMinLen $ "
604                  "olcIndexSubstrAnyLen $ olcIndexSubstrAnyStep $ olcLocalSSF $ "
605                  "olcLogLevel $ "
606                  "olcPasswordCryptSaltFormat $ olcPasswordHash $ olcPidFile $ "
607                  "olcPluginLogFile $ olcReadOnly $ olcReferral $ "
608                  "olcReplicaPidFile $ olcReplicaArgsFile $ olcReplicationInterval $ "
609                  "olcReplogFile $ olcRequires $ olcRestrict $ olcReverseLookup $ "
610                  "olcRootDSE $ "
611                  "olcSaslHost $ olcSaslRealm $ olcSaslSecProps $ "
612                  "olcSecurity $ olcSizeLimit $ "
613                  "olcSockbufMaxIncoming $ olcSockbufMaxIncomingAuth $ olcSrvtab $ "
614                  "olcThreads $ olcTimeLimit $ olcTLSCACertificateFile $ "
615                  "olcTLSCACertificatePath $ olcTLSCertificateFile $ "
616                  "olcTLSCertificateKeyFile $ olcTLSCipherSuite $ olcTLSCRLCheck $ "
617                  "olcTLSRandFile $ olcTLSVerifyClient $ "
618                  "olcObjectIdentifier $ olcAttributeTypes $ olcObjectClasses $ "
619                  "olcDitContentRules ) )", Cft_Global },
620         { "( OLcfgGlOc:2 "
621                 "NAME 'olcSchemaConfig' "
622                 "DESC 'OpenLDAP schema object' "
623                 "SUP olcConfig STRUCTURAL "
624                 "MAY ( cn $ olcObjectIdentifier $ olcAttributeTypes $ "
625                  "olcObjectClasses $ olcDitContentRules ) )",
626                         Cft_Schema, NULL, cfAddSchema },
627         { "( OLcfgGlOc:3 "
628                 "NAME 'olcBackendConfig' "
629                 "DESC 'OpenLDAP Backend-specific options' "
630                 "SUP olcConfig STRUCTURAL "
631                 "MUST olcBackend )", Cft_Backend, NULL, cfAddBackend },
632         { "( OLcfgGlOc:4 "
633                 "NAME 'olcDatabaseConfig' "
634                 "DESC 'OpenLDAP Database-specific options' "
635                 "SUP olcConfig STRUCTURAL "
636                 "MUST olcDatabase "
637                 "MAY ( olcSuffix $ olcAccess $ olcLastMod $ olcLimits $ "
638                  "olcMaxDerefDepth $ olcPlugin $ olcReadOnly $ olcReplica $ "
639                  "olcReplogFile $ olcRequires $ olcRestrict $ olcRootDN $ olcRootPW $ "
640                  "olcSchemaDN $ olcSecurity $ olcSizeLimit $ olcSyncrepl $ "
641                  "olcTimeLimit $ olcUpdateDN $ olcUpdateRef ) )",
642                         Cft_Database, NULL, cfAddDatabase },
643         { "( OLcfgGlOc:5 "
644                 "NAME 'olcOverlayConfig' "
645                 "DESC 'OpenLDAP Overlay-specific options' "
646                 "SUP olcConfig STRUCTURAL "
647                 "MUST olcOverlay )", Cft_Overlay, NULL, cfAddOverlay },
648         { "( OLcfgGlOc:6 "
649                 "NAME 'olcIncludeFile' "
650                 "DESC 'OpenLDAP configuration include file' "
651                 "SUP olcConfig STRUCTURAL "
652                 "MUST olcInclude "
653                 "MAY ( cn $ olcRootDSE ) )",
654                 Cft_Include, NULL, cfAddInclude },
655         /* This should be STRUCTURAL like all the other database classes, but
656          * that would mean inheriting all of the olcDatabaseConfig attributes,
657          * which causes them to be merged twice in config_build_entry.
658          */
659         { "( OLcfgGlOc:7 "
660                 "NAME 'olcFrontendConfig' "
661                 "DESC 'OpenLDAP frontend configuration' "
662                 "AUXILIARY "
663                 "MAY olcDefaultSearchBase )",
664                 Cft_Database, NULL, NULL },
665 #ifdef SLAPD_MODULES
666         { "( OLcfgGlOc:8 "
667                 "NAME 'olcModuleList' "
668                 "DESC 'OpenLDAP dynamic module info' "
669                 "SUP olcConfig STRUCTURAL "
670                 "MAY ( cn $ olcModulePath $ olcModuleLoad ) )",
671                 Cft_Module, NULL, cfAddModule },
672 #endif
673         { NULL, 0, NULL }
674 };
675
676 static int
677 config_generic(ConfigArgs *c) {
678         char *p;
679         int i;
680
681         if ( c->op == SLAP_CONFIG_EMIT ) {
682                 int rc = 0;
683                 switch(c->type) {
684                 case CFG_CONCUR:
685                         c->value_int = ldap_pvt_thread_get_concurrency();
686                         break;
687                 case CFG_THREADS:
688                         c->value_int = connection_pool_max;
689                         break;
690                 case CFG_SALT:
691                         if ( passwd_salt )
692                                 c->value_string = ch_strdup( passwd_salt );
693                         else
694                                 rc = 1;
695                         break;
696                 case CFG_LIMITS:
697                         if ( c->be->be_limits ) {
698                                 char buf[4096*3];
699                                 struct berval bv;
700                                 int i;
701
702                                 for ( i=0; c->be->be_limits[i]; i++ ) {
703                                         bv.bv_len = sprintf( buf, IFMT, i );
704                                         bv.bv_val = buf+bv.bv_len;
705                                         limits_unparse( c->be->be_limits[i], &bv );
706                                         bv.bv_len += bv.bv_val - buf;
707                                         bv.bv_val = buf;
708                                         value_add_one( &c->rvalue_vals, &bv );
709                                 }
710                         }
711                         if ( !c->rvalue_vals ) rc = 1;
712                         break;
713                 case CFG_RO:
714                         c->value_int = (c->be->be_restrictops & SLAP_RESTRICT_OP_WRITES) ==
715                                 SLAP_RESTRICT_OP_WRITES;
716                         break;
717                 case CFG_AZPOLICY:
718                         c->value_string = ch_strdup( slap_sasl_getpolicy());
719                         break;
720                 case CFG_AZREGEXP:
721                         slap_sasl_regexp_unparse( &c->rvalue_vals );
722                         if ( !c->rvalue_vals ) rc = 1;
723                         break;
724 #ifdef HAVE_CYRUS_SASL
725                 case CFG_SASLSECP: {
726                         struct berval bv = BER_BVNULL;
727                         slap_sasl_secprops_unparse( &bv );
728                         if ( !BER_BVISNULL( &bv )) {
729                                 ber_bvarray_add( &c->rvalue_vals, &bv );
730                         } else {
731                                 rc = 1;
732                         }
733                         }
734                         break;
735 #endif
736                 case CFG_DEPTH:
737                         c->value_int = c->be->be_max_deref_depth;
738                         break;
739                 case CFG_OID: {
740                         ConfigFile *cf = c->private;
741                         if ( !cf )
742                                 oidm_unparse( &c->rvalue_vals, NULL, NULL, 1 );
743                         else if ( cf->c_om_head )
744                                 oidm_unparse( &c->rvalue_vals, cf->c_om_head,
745                                         cf->c_om_tail, 0 );
746                         if ( !c->rvalue_vals )
747                                 rc = 1;
748                         }
749                         break;
750                 case CFG_OC: {
751                         ConfigFile *cf = c->private;
752                         if ( !cf )
753                                 oc_unparse( &c->rvalue_vals, NULL, NULL, 1 );
754                         else if ( cf->c_oc_head )
755                                 oc_unparse( &c->rvalue_vals, cf->c_oc_head,
756                                         cf->c_oc_tail, 0 );
757                         if ( !c->rvalue_vals )
758                                 rc = 1;
759                         }
760                         break;
761                 case CFG_ATTR: {
762                         ConfigFile *cf = c->private;
763                         if ( !cf )
764                                 at_unparse( &c->rvalue_vals, NULL, NULL, 1 );
765                         else if ( cf->c_at_head )
766                                 at_unparse( &c->rvalue_vals, cf->c_at_head,
767                                         cf->c_at_tail, 0 );
768                         if ( !c->rvalue_vals )
769                                 rc = 1;
770                         }
771                         break;
772                 case CFG_DIT: {
773                         ConfigFile *cf = c->private;
774                         if ( !cf )
775                                 cr_unparse( &c->rvalue_vals, NULL, NULL, 1 );
776                         else if ( cf->c_cr_head )
777                                 cr_unparse( &c->rvalue_vals, cf->c_cr_head,
778                                         cf->c_cr_tail, 0 );
779                         if ( !c->rvalue_vals )
780                                 rc = 1;
781                         }
782                         break;
783                         
784                 case CFG_ACL: {
785                         AccessControl *a;
786                         char *src, *dst, ibuf[11];
787                         struct berval bv, abv;
788                         for (i=0, a=c->be->be_acl; a; i++,a=a->acl_next) {
789                                 abv.bv_len = sprintf( ibuf, IFMT, i );
790                                 acl_unparse( a, &bv );
791                                 abv.bv_val = ch_malloc( abv.bv_len + bv.bv_len + 1 );
792                                 AC_MEMCPY( abv.bv_val, ibuf, abv.bv_len );
793                                 /* Turn TAB / EOL into plain space */
794                                 for (src=bv.bv_val,dst=abv.bv_val+abv.bv_len; *src; src++) {
795                                         if (isspace(*src)) *dst++ = ' ';
796                                         else *dst++ = *src;
797                                 }
798                                 *dst = '\0';
799                                 if (dst[-1] == ' ') {
800                                         dst--;
801                                         *dst = '\0';
802                                 }
803                                 abv.bv_len = dst - abv.bv_val;
804                                 ber_bvarray_add( &c->rvalue_vals, &abv );
805                         }
806                         rc = (!i);
807                         break;
808                 }
809                 case CFG_REPLOG:
810                         if ( c->be->be_replogfile )
811                                 c->value_string = ch_strdup( c->be->be_replogfile );
812                         break;
813                 case CFG_ROOTDSE: {
814                         ConfigFile *cf = c->private;
815                         if ( cf->c_dseFiles ) {
816                                 value_add( &c->rvalue_vals, cf->c_dseFiles );
817                         } else {
818                                 rc = 1;
819                         }
820                         }
821                         break;
822                 case CFG_LOGFILE:
823                         if ( logfileName )
824                                 c->value_string = ch_strdup( logfileName );
825                         else
826                                 rc = 1;
827                         break;
828                 case CFG_LASTMOD:
829                         c->value_int = (SLAP_NOLASTMOD(c->be) == 0);
830                         break;
831                 case CFG_SSTR_IF_MAX:
832                         c->value_int = index_substr_if_maxlen;
833                         break;
834                 case CFG_SSTR_IF_MIN:
835                         c->value_int = index_substr_if_minlen;
836                         break;
837 #ifdef SLAPD_MODULES
838                 case CFG_MODLOAD: {
839                         ModPaths *mp = c->private;
840                         if (mp->mp_loads) {
841                                 int i;
842                                 for (i=0; !BER_BVISNULL(&mp->mp_loads[i]); i++) {
843                                         struct berval bv;
844                                         bv.bv_val = c->log;
845                                         bv.bv_len = sprintf( bv.bv_val, IFMT "%s", i,
846                                                 mp->mp_loads[i].bv_val );
847                                         value_add_one( &c->rvalue_vals, &bv );
848                                 }
849                         }
850
851                         rc = c->rvalue_vals ? 0 : 1;
852                         }
853                         break;
854                 case CFG_MODPATH: {
855                         ModPaths *mp = c->private;
856                         if ( !BER_BVISNULL( &mp->mp_path ))
857                                 value_add_one( &c->rvalue_vals, &mp->mp_path );
858
859                         rc = c->rvalue_vals ? 0 : 1;
860                         }
861                         break;
862 #endif
863 #ifdef LDAP_SLAPI
864                 case CFG_PLUGIN:
865                         slapi_int_plugin_unparse( c->be, &c->rvalue_vals );
866                         if ( !c->rvalue_vals ) rc = 1;
867                         break;
868 #endif
869 #ifdef SLAP_AUTH_REWRITE
870                 case CFG_REWRITE:
871                         if ( authz_rewrites ) {
872                                 struct berval bv, idx;
873                                 char ibuf[32];
874                                 int i;
875
876                                 idx.bv_val = ibuf;
877                                 for ( i=0; !BER_BVISNULL( &authz_rewrites[i] ); i++ ) {
878                                         idx.bv_len = sprintf( idx.bv_val, IFMT, i );
879                                         bv.bv_len = idx.bv_len + authz_rewrites[i].bv_len;
880                                         bv.bv_val = ch_malloc( bv.bv_len + 1 );
881                                         strcpy( bv.bv_val, idx.bv_val );
882                                         strcpy( bv.bv_val+idx.bv_len, authz_rewrites[i].bv_val );
883                                         ber_bvarray_add( &c->rvalue_vals, &bv );
884                                 }
885                         }
886                         if ( !c->rvalue_vals ) rc = 1;
887                         break;
888 #endif
889                 default:
890                         rc = 1;
891                 }
892                 return rc;
893         } else if ( c->op == LDAP_MOD_DELETE ) {
894                 int rc = 0;
895                 switch(c->type) {
896                 /* single-valued attrs, no-ops */
897                 case CFG_CONCUR:
898                 case CFG_THREADS:
899                 case CFG_RO:
900                 case CFG_AZPOLICY:
901                 case CFG_DEPTH:
902                 case CFG_LASTMOD:
903                 case CFG_SASLSECP:
904                 case CFG_SSTR_IF_MAX:
905                 case CFG_SSTR_IF_MIN:
906                         break;
907
908                 /* no-ops, requires slapd restart */
909                 case CFG_PLUGIN:
910                 case CFG_MODLOAD:
911                 case CFG_AZREGEXP:
912                 case CFG_REWRITE:
913                         sprintf(c->log, "change requires slapd restart");
914                         break;
915
916                 case CFG_SALT:
917                         ch_free( passwd_salt );
918                         passwd_salt = NULL;
919                         break;
920
921                 case CFG_REPLOG:
922                         ch_free( c->be->be_replogfile );
923                         c->be->be_replogfile = NULL;
924                         break;
925
926                 case CFG_LOGFILE:
927                         ch_free( logfileName );
928                         logfileName = NULL;
929                         break;
930
931                 case CFG_ACL:
932                         if ( c->valx < 0 ) {
933                                 AccessControl *end;
934                                 if ( c->be == frontendDB )
935                                         end = NULL;
936                                 else
937                                         end = frontendDB->be_acl;
938                                 acl_destroy( c->be->be_acl, end );
939                         } else {
940                                 AccessControl **prev, *a;
941                                 int i;
942                                 for (i=0, prev = &c->be->be_acl; i < c->valx;
943                                         i++ ) {
944                                         a = *prev;
945                                         prev = &a->acl_next;
946                                 }
947                                 a = *prev;
948                                 *prev = a->acl_next;
949                                 acl_free( a );
950                         }
951                         break;
952
953                 case CFG_LIMITS:
954                         /* FIXME: there is no limits_free function */
955                 case CFG_ATOPT:
956                         /* FIXME: there is no ad_option_free function */
957                 case CFG_ROOTDSE:
958                         /* FIXME: there is no way to remove attributes added by
959                                 a DSE file */
960                 case CFG_OID:
961                 case CFG_OC:
962                 case CFG_DIT:
963                 case CFG_ATTR:
964                 case CFG_MODPATH:
965                 default:
966                         rc = 1;
967                         break;
968                 }
969                 return rc;
970         }
971
972         p = strchr(c->line,'(' /*')'*/);
973
974         switch(c->type) {
975                 case CFG_BACKEND:
976                         if(!(c->bi = backend_info(c->argv[1]))) {
977                                 sprintf( c->msg, "<%s> failed init", c->argv[0] );
978                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
979                                         c->log, c->msg, c->argv[1] );
980                                 return(1);
981                         }
982                         break;
983
984                 case CFG_DATABASE:
985                         c->bi = NULL;
986                         /* NOTE: config is always the first backend!
987                          */
988                         if ( !strcasecmp( c->argv[1], "config" )) {
989                                 c->be = LDAP_STAILQ_FIRST(&backendDB);
990                         } else if ( !strcasecmp( c->argv[1], "frontend" )) {
991                                 c->be = frontendDB;
992                         } else {
993                                 c->be = backend_db_init(c->argv[1]);
994                                 if ( !c->be ) {
995                                         sprintf( c->msg, "<%s> failed init", c->argv[0] );
996                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
997                                                 c->log, c->msg, c->argv[1] );
998                                         return(1);
999                                 }
1000                         }
1001                         break;
1002
1003                 case CFG_CONCUR:
1004                         ldap_pvt_thread_set_concurrency(c->value_int);
1005                         break;
1006
1007                 case CFG_THREADS:
1008                         ldap_pvt_thread_pool_maxthreads(&connection_pool, c->value_int);
1009                         connection_pool_max = c->value_int;     /* save for reference */
1010                         break;
1011
1012                 case CFG_SALT:
1013                         if ( passwd_salt ) ch_free( passwd_salt );
1014                         passwd_salt = c->value_string;
1015                         lutil_salt_format(passwd_salt);
1016                         break;
1017
1018                 case CFG_LIMITS:
1019                         if(limits_parse(c->be, c->fname, c->lineno, c->argc, c->argv))
1020                                 return(1);
1021                         break;
1022
1023                 case CFG_RO:
1024                         if(c->value_int)
1025                                 c->be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1026                         else
1027                                 c->be->be_restrictops &= ~SLAP_RESTRICT_OP_WRITES;
1028                         break;
1029
1030                 case CFG_AZPOLICY:
1031                         ch_free(c->value_string);
1032                         if (slap_sasl_setpolicy( c->argv[1] )) {
1033                                 sprintf( c->msg, "<%s> unable to parse value", c->argv[0] );
1034                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1035                                         c->log, c->msg, c->argv[1] );
1036                                 return(1);
1037                         }
1038                         break;
1039                 
1040                 case CFG_AZREGEXP:
1041                         if (slap_sasl_regexp_config( c->argv[1], c->argv[2] ))
1042                                 return(1);
1043                         break;
1044                                 
1045 #ifdef HAVE_CYRUS_SASL
1046                 case CFG_SASLSECP:
1047                         {
1048                         char *txt = slap_sasl_secprops( c->argv[1] );
1049                         if ( txt ) {
1050                                 snprintf( c->msg, sizeof(c->msg), "<%s> %s",
1051                                         c->argv[0], txt );
1052                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
1053                                 return(1);
1054                         }
1055                         break;
1056                         }
1057 #endif
1058
1059                 case CFG_DEPTH:
1060                         c->be->be_max_deref_depth = c->value_int;
1061                         break;
1062
1063                 case CFG_OID: {
1064                         OidMacro *om;
1065
1066                         if(parse_oidm(c->fname, c->lineno, c->argc, c->argv, 1, &om))
1067                                 return(1);
1068                         if (!cfn->c_om_head) cfn->c_om_head = om;
1069                         cfn->c_om_tail = om;
1070                         }
1071                         break;
1072
1073                 case CFG_OC: {
1074                         ObjectClass *oc;
1075
1076                         if(parse_oc(c->fname, c->lineno, p, c->argv, &oc)) return(1);
1077                         if (!cfn->c_oc_head) cfn->c_oc_head = oc;
1078                         cfn->c_oc_tail = oc;
1079                         }
1080                         break;
1081
1082                 case CFG_DIT: {
1083                         ContentRule *cr;
1084
1085                         if(parse_cr(c->fname, c->lineno, p, c->argv, &cr)) return(1);
1086                         if (!cfn->c_cr_head) cfn->c_cr_head = cr;
1087                         cfn->c_cr_tail = cr;
1088                         }
1089                         break;
1090
1091                 case CFG_ATTR: {
1092                         AttributeType *at;
1093
1094                         if(parse_at(c->fname, c->lineno, p, c->argv, &at)) return(1);
1095                         if (!cfn->c_at_head) cfn->c_at_head = at;
1096                         cfn->c_at_tail = at;
1097                         }
1098                         break;
1099
1100                 case CFG_ATOPT:
1101                         ad_define_option(NULL, NULL, 0);
1102                         for(i = 1; i < c->argc; i++)
1103                                 if(ad_define_option(c->argv[i], c->fname, c->lineno))
1104                                         return(1);
1105                         break;
1106
1107                 case CFG_ACL:
1108                         parse_acl(c->be, c->fname, c->lineno, c->argc, c->argv, c->valx);
1109                         break;
1110
1111                 case CFG_REPLOG:
1112                         if(SLAP_MONITOR(c->be)) {
1113                                 Debug(LDAP_DEBUG_ANY, "%s: "
1114                                         "\"replogfile\" should not be used "
1115                                         "inside monitor database\n",
1116                                         c->log, 0, 0);
1117                                 return(0);      /* FIXME: should this be an error? */
1118                         }
1119
1120                         c->be->be_replogfile = c->value_string;
1121                         break;
1122
1123                 case CFG_ROOTDSE:
1124                         if(read_root_dse_file(c->argv[1])) {
1125                                 sprintf( c->msg, "<%s> could not read file", c->argv[0] );
1126                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1127                                         c->log, c->msg, c->argv[1] );
1128                                 return(1);
1129                         }
1130                         {
1131                                 struct berval bv;
1132                                 ber_str2bv( c->argv[1], 0, 1, &bv );
1133                                 ber_bvarray_add( &cfn->c_dseFiles, &bv );
1134                         }
1135                         break;
1136
1137                 case CFG_LOGFILE: {
1138                                 FILE *logfile;
1139                                 if ( logfileName ) ch_free( logfileName );
1140                                 logfileName = c->value_string;
1141                                 logfile = fopen(logfileName, "w");
1142                                 if(logfile) lutil_debug_file(logfile);
1143                         } break;
1144
1145                 case CFG_LASTMOD:
1146                         if(SLAP_NOLASTMODCMD(c->be)) {
1147                                 sprintf( c->msg, "<%s> not available for %s database",
1148                                         c->argv[0], c->be->bd_info->bi_type );
1149                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1150                                         c->log, c->msg, 0 );
1151                                 return(1);
1152                         }
1153                         if(c->value_int)
1154                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_NOLASTMOD;
1155                         else
1156                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NOLASTMOD;
1157                         break;
1158
1159                 case CFG_SSTR_IF_MAX:
1160                         if (c->value_int < index_substr_if_minlen) {
1161                                 sprintf( c->msg, "<%s> invalid value", c->argv[0] );
1162                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1163                                         c->log, c->msg, c->value_int );
1164                                 return(1);
1165                         }
1166                         index_substr_if_maxlen = c->value_int;
1167                         break;
1168
1169                 case CFG_SSTR_IF_MIN:
1170                         if (c->value_int > index_substr_if_maxlen) {
1171                                 sprintf( c->msg, "<%s> invalid value", c->argv[0] );
1172                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1173                                         c->log, c->msg, c->value_int );
1174                                 return(1);
1175                         }
1176                         index_substr_if_minlen = c->value_int;
1177                         break;
1178
1179 #ifdef SLAPD_MODULES
1180                 case CFG_MODLOAD:
1181                         /* If we're just adding a module on an existing modpath,
1182                          * make sure we've selected the current path.
1183                          */
1184                         if ( c->op == LDAP_MOD_ADD && c->private && modcur != c->private ) {
1185                                 modcur = c->private;
1186                                 /* This should never fail */
1187                                 if ( module_path( modcur->mp_path.bv_val )) {
1188                                         sprintf( c->msg, "<%s> module path no longer valid",
1189                                                 c->argv[0] );
1190                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1191                                                 c->log, c->msg, modcur->mp_path.bv_val );
1192                                         return(1);
1193                                 }
1194                         }
1195                         if(module_load(c->argv[1], c->argc - 2, (c->argc > 2) ? c->argv + 2 : NULL))
1196                                 return(1);
1197                         /* Record this load on the current path */
1198                         {
1199                                 struct berval bv;
1200                                 char *ptr;
1201                                 if ( c->op == SLAP_CONFIG_ADD ) {
1202                                         ptr = c->line + STRLENOF("moduleload");
1203                                         while (!isspace(*ptr)) ptr++;
1204                                         while (isspace(*ptr)) ptr++;
1205                                 } else {
1206                                         ptr = c->line;
1207                                 }
1208                                 ber_str2bv(ptr, 0, 1, &bv);
1209                                 ber_bvarray_add( &modcur->mp_loads, &bv );
1210                         }
1211                         break;
1212
1213                 case CFG_MODPATH:
1214                         if(module_path(c->argv[1])) return(1);
1215                         /* Record which path was used with each module */
1216                         {
1217                                 ModPaths *mp;
1218
1219                                 if (!modpaths.mp_loads) {
1220                                         mp = &modpaths;
1221                                 } else {
1222                                         mp = ch_malloc( sizeof( ModPaths ));
1223                                         modlast->mp_next = mp;
1224                                 }
1225                                 ber_str2bv(c->argv[1], 0, 1, &mp->mp_path);
1226                                 mp->mp_next = NULL;
1227                                 mp->mp_loads = NULL;
1228                                 modlast = mp;
1229                                 c->private = mp;
1230                                 modcur = mp;
1231                         }
1232                         
1233                         break;
1234 #endif
1235
1236 #ifdef LDAP_SLAPI
1237                 case CFG_PLUGIN:
1238                         if(slapi_int_read_config(c->be, c->fname, c->lineno, c->argc, c->argv) != LDAP_SUCCESS)
1239                                 return(1);
1240                         slapi_plugins_used++;
1241                         break;
1242 #endif
1243
1244 #ifdef SLAP_AUTH_REWRITE
1245                 case CFG_REWRITE: {
1246                         struct berval bv;
1247                         char *line;
1248                         
1249                         if(slap_sasl_rewrite_config(c->fname, c->lineno, c->argc, c->argv))
1250                                 return(1);
1251
1252                         if ( c->argc > 1 ) {
1253                                 char    *s;
1254
1255                                 /* quote all args but the first */
1256                                 line = ldap_charray2str( c->argv, "\" \"" );
1257                                 ber_str2bv( line, 0, 0, &bv );
1258                                 s = strchr( bv.bv_val, '"' );
1259                                 assert( s != NULL );
1260                                 /* move the trailing quote of argv[0] to the end */
1261                                 AC_MEMCPY( s, s + 1, bv.bv_len - ( s - bv.bv_val ) );
1262                                 bv.bv_val[ bv.bv_len - 1 ] = '"';
1263
1264                         } else {
1265                                 ber_str2bv( c->argv[ 0 ], 0, 1, &bv );
1266                         }
1267                         
1268                         ber_bvarray_add( &authz_rewrites, &bv );
1269                         }
1270                         break;
1271 #endif
1272
1273
1274                 default:
1275                         Debug( SLAPD_DEBUG_CONFIG_ERROR,
1276                                 "%s: unknown CFG_TYPE %d"
1277                                 SLAPD_CONF_UNKNOWN_IGNORED ".\n",
1278                                 c->log, c->type, 0 );
1279 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
1280                         return 1;
1281 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
1282
1283         }
1284         return(0);
1285 }
1286
1287
1288 static int
1289 config_fname(ConfigArgs *c) {
1290         if(c->op == SLAP_CONFIG_EMIT) {
1291                 if (c->private) {
1292                         ConfigFile *cf = c->private;
1293                         value_add_one( &c->rvalue_vals, &cf->c_file );
1294                         return 0;
1295                 }
1296                 return 1;
1297         }
1298         return(0);
1299 }
1300
1301 static int
1302 config_cfdir(ConfigArgs *c) {
1303         if(c->op == SLAP_CONFIG_EMIT) {
1304                 if ( !BER_BVISEMPTY( &cfdir )) {
1305                         value_add_one( &c->rvalue_vals, &cfdir );
1306                         return 0;
1307                 }
1308                 return 1;
1309         }
1310         return(0);
1311 }
1312
1313 static int
1314 config_search_base(ConfigArgs *c) {
1315         if(c->op == SLAP_CONFIG_EMIT) {
1316                 int rc = 1;
1317                 if (!BER_BVISEMPTY(&default_search_base)) {
1318                         value_add_one(&c->rvalue_vals, &default_search_base);
1319                         value_add_one(&c->rvalue_nvals, &default_search_nbase);
1320                         rc = 0;
1321                 }
1322                 return rc;
1323         } else if( c->op == LDAP_MOD_DELETE ) {
1324                 ch_free( default_search_base.bv_val );
1325                 ch_free( default_search_nbase.bv_val );
1326                 BER_BVZERO( &default_search_base );
1327                 BER_BVZERO( &default_search_nbase );
1328                 return 0;
1329         }
1330
1331         if(c->bi || c->be != frontendDB) {
1332                 Debug(LDAP_DEBUG_ANY, "%s: defaultSearchBase line must appear "
1333                         "prior to any backend or database definition\n",
1334                         c->log, 0, 0);
1335                 return(1);
1336         }
1337
1338         if(default_search_nbase.bv_len) {
1339                 free(default_search_base.bv_val);
1340                 free(default_search_nbase.bv_val);
1341         }
1342
1343         default_search_base = c->value_dn;
1344         default_search_nbase = c->value_ndn;
1345         return(0);
1346 }
1347
1348 static int
1349 config_passwd_hash(ConfigArgs *c) {
1350         int i;
1351         if (c->op == SLAP_CONFIG_EMIT) {
1352                 struct berval bv;
1353                 for (i=0; default_passwd_hash && default_passwd_hash[i]; i++) {
1354                         ber_str2bv(default_passwd_hash[i], 0, 0, &bv);
1355                         value_add_one(&c->rvalue_vals, &bv);
1356                 }
1357                 return i ? 0 : 1;
1358         } else if ( c->op == LDAP_MOD_DELETE ) {
1359                 if ( c->valx < 0 ) {
1360                         ldap_charray_free( default_passwd_hash );
1361                         default_passwd_hash = NULL;
1362                 } else {
1363                         i = c->valx;
1364                         ch_free( default_passwd_hash[i] );
1365                         for (; default_passwd_hash[i]; i++ )
1366                                 default_passwd_hash[i] = default_passwd_hash[i+1];
1367                 }
1368                 return 0;
1369         }
1370         if(default_passwd_hash) {
1371                 Debug(LDAP_DEBUG_ANY, "%s: "
1372                         "already set default password_hash\n",
1373                         c->log, 0, 0);
1374                 return(1);
1375         }
1376         for(i = 1; i < c->argc; i++) {
1377                 if(!lutil_passwd_scheme(c->argv[i])) {
1378                         sprintf( c->msg, "<%s> schema not available", c->argv[0] );
1379                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1380                                 c->log, c->msg, c->argv[i]);
1381                 } else {
1382                         ldap_charray_add(&default_passwd_hash, c->argv[i]);
1383                 }
1384                 if(!default_passwd_hash) {
1385                         sprintf( c->msg, "<%s> no valid hashes found", c->argv[0] );
1386                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1387                                 c->log, c->msg, 0 );
1388                         return(1);
1389                 }
1390         }
1391         return(0);
1392 }
1393
1394 static int
1395 config_schema_dn(ConfigArgs *c) {
1396         if ( c->op == SLAP_CONFIG_EMIT ) {
1397                 int rc = 1;
1398                 if ( !BER_BVISEMPTY( &c->be->be_schemadn )) {
1399                         value_add_one(&c->rvalue_vals, &c->be->be_schemadn);
1400                         value_add_one(&c->rvalue_nvals, &c->be->be_schemandn);
1401                         rc = 0;
1402                 }
1403                 return rc;
1404         } else if ( c->op == LDAP_MOD_DELETE ) {
1405                 ch_free( c->be->be_schemadn.bv_val );
1406                 ch_free( c->be->be_schemandn.bv_val );
1407                 BER_BVZERO( &c->be->be_schemadn );
1408                 BER_BVZERO( &c->be->be_schemandn );
1409                 return 0;
1410         }
1411         ch_free( c->be->be_schemadn.bv_val );
1412         ch_free( c->be->be_schemandn.bv_val );
1413         c->be->be_schemadn = c->value_dn;
1414         c->be->be_schemandn = c->value_ndn;
1415         return(0);
1416 }
1417
1418 static int
1419 config_sizelimit(ConfigArgs *c) {
1420         int i, rc = 0;
1421         char *next;
1422         struct slap_limits_set *lim = &c->be->be_def_limit;
1423         if (c->op == SLAP_CONFIG_EMIT) {
1424                 char buf[8192];
1425                 struct berval bv;
1426                 bv.bv_val = buf;
1427                 bv.bv_len = 0;
1428                 limits_unparse_one( lim, SLAP_LIMIT_SIZE, &bv );
1429                 if ( !BER_BVISEMPTY( &bv ))
1430                         value_add_one( &c->rvalue_vals, &bv );
1431                 else
1432                         rc = 1;
1433                 return rc;
1434         } else if ( c->op == LDAP_MOD_DELETE ) {
1435                 /* Reset to defaults */
1436                 lim->lms_s_soft = SLAPD_DEFAULT_SIZELIMIT;
1437                 lim->lms_s_hard = 0;
1438                 lim->lms_s_unchecked = -1;
1439                 lim->lms_s_pr = 0;
1440                 lim->lms_s_pr_hide = 0;
1441                 lim->lms_s_pr_total = 0;
1442                 return 0;
1443         }
1444         for(i = 1; i < c->argc; i++) {
1445                 if(!strncasecmp(c->argv[i], "size", 4)) {
1446                         rc = limits_parse_one(c->argv[i], lim);
1447                         if ( rc ) {
1448                                 sprintf( c->msg, "<%s> unable to parse value", c->argv[0] );
1449                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1450                                         c->log, c->msg, c->argv[i]);
1451                                 return(1);
1452                         }
1453                 } else {
1454                         if(!strcasecmp(c->argv[i], "unlimited")) {
1455                                 lim->lms_s_soft = -1;
1456                         } else {
1457                                 lim->lms_s_soft = strtol(c->argv[i], &next, 0);
1458                                 if(next == c->argv[i]) {
1459                                         sprintf( c->msg, "<%s> unable to parse limit", c->argv[0]);
1460                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1461                                                 c->log, c->msg, c->argv[i]);
1462                                         return(1);
1463                                 } else if(next[0] != '\0') {
1464                                         Debug( SLAPD_DEBUG_CONFIG_ERROR, "%s: "
1465                                                 "trailing chars \"%s\" in \"sizelimit <limit>\" line"
1466                                                 SLAPD_CONF_UNKNOWN_IGNORED ".\n",
1467                                                 c->log, next, 0);
1468 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
1469                                         return 1;
1470 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
1471                                 }
1472                         }
1473                         lim->lms_s_hard = 0;
1474                 }
1475         }
1476         return(0);
1477 }
1478
1479 static int
1480 config_timelimit(ConfigArgs *c) {
1481         int i, rc = 0;
1482         char *next;
1483         struct slap_limits_set *lim = &c->be->be_def_limit;
1484         if (c->op == SLAP_CONFIG_EMIT) {
1485                 char buf[8192];
1486                 struct berval bv;
1487                 bv.bv_val = buf;
1488                 bv.bv_len = 0;
1489                 limits_unparse_one( lim, SLAP_LIMIT_TIME, &bv );
1490                 if ( !BER_BVISEMPTY( &bv ))
1491                         value_add_one( &c->rvalue_vals, &bv );
1492                 else
1493                         rc = 1;
1494                 return rc;
1495         } else if ( c->op == LDAP_MOD_DELETE ) {
1496                 /* Reset to defaults */
1497                 lim->lms_t_soft = SLAPD_DEFAULT_TIMELIMIT;
1498                 lim->lms_t_hard = 0;
1499                 return 0;
1500         }
1501         for(i = 1; i < c->argc; i++) {
1502                 if(!strncasecmp(c->argv[i], "time", 4)) {
1503                         rc = limits_parse_one(c->argv[i], lim);
1504                         if ( rc ) {
1505                                 sprintf( c->msg, "<%s> unable to parse value", c->argv[0] );
1506                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1507                                         c->log, c->msg, c->argv[i]);
1508                                 return(1);
1509                         }
1510                 } else {
1511                         if(!strcasecmp(c->argv[i], "unlimited")) {
1512                                 lim->lms_t_soft = -1;
1513                         } else {
1514                                 lim->lms_t_soft = strtol(c->argv[i], &next, 0);
1515                                 if(next == c->argv[i]) {
1516                                         sprintf( c->msg, "<%s> unable to parse limit", c->argv[0]);
1517                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1518                                                 c->log, c->msg, c->argv[i]);
1519                                         return(1);
1520                                 } else if(next[0] != '\0') {
1521                                         Debug( SLAPD_DEBUG_CONFIG_ERROR, "%s: "
1522                                                 "trailing chars \"%s\" in \"timelimit <limit>\" line"
1523                                                 SLAPD_CONF_UNKNOWN_IGNORED ".\n",
1524                                                 c->log, next, 0);
1525 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
1526                                         return 1;
1527 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
1528                                 }
1529                         }
1530                         lim->lms_t_hard = 0;
1531                 }
1532         }
1533         return(0);
1534 }
1535
1536 static int
1537 config_overlay(ConfigArgs *c) {
1538         slap_overinfo *oi;
1539         if (c->op == SLAP_CONFIG_EMIT) {
1540                 return 1;
1541         } else if ( c->op == LDAP_MOD_DELETE ) {
1542                 assert(0);
1543         }
1544         if(c->argv[1][0] == '-' && overlay_config(c->be, &c->argv[1][1])) {
1545                 /* log error */
1546                 Debug( SLAPD_DEBUG_CONFIG_ERROR, "%s: (optional) %s overlay \"%s\" configuration failed"
1547                         SLAPD_CONF_UNKNOWN_IGNORED ".\n",
1548                         c->log, c->be == frontendDB ? "global " : "", &c->argv[1][1]);
1549 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
1550                 return 1;
1551 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
1552         } else if(overlay_config(c->be, c->argv[1])) {
1553                 return(1);
1554         }
1555         /* Setup context for subsequent config directives.
1556          * The newly added overlay is at the head of the list.
1557          */
1558         oi = (slap_overinfo *)c->be->bd_info;
1559         c->bi = &oi->oi_list->on_bi;
1560         return(0);
1561 }
1562
1563 static int
1564 config_suffix(ConfigArgs *c)
1565 {
1566         Backend *tbe;
1567         struct berval pdn, ndn;
1568         char    *notallowed = NULL;
1569
1570         if ( c->be == frontendDB ) {
1571                 notallowed = "frontend";
1572
1573         } else if ( SLAP_MONITOR(c->be) ) {
1574                 notallowed = "monitor";
1575
1576         } else if ( SLAP_CONFIG(c->be) ) {
1577                 notallowed = "config";
1578         }
1579
1580         if ( notallowed != NULL ) {
1581                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
1582
1583                 switch ( c->op ) {
1584                 case LDAP_MOD_ADD:
1585                 case LDAP_MOD_DELETE:
1586                 case LDAP_MOD_REPLACE:
1587                 case LDAP_MOD_INCREMENT:
1588                 case SLAP_CONFIG_ADD:
1589                         if ( !BER_BVISNULL( &c->value_dn ) ) {
1590                                 snprintf( buf, sizeof( buf ), "<%s> ",
1591                                                 c->value_dn.bv_val );
1592                         }
1593
1594                         Debug(LDAP_DEBUG_ANY,
1595                                 "%s: suffix %snot allowed in %s database.\n",
1596                                 c->log, buf, notallowed );
1597                         break;
1598
1599                 case SLAP_CONFIG_EMIT:
1600                         /* don't complain when emitting... */
1601                         break;
1602
1603                 default:
1604                         /* FIXME: don't know what values may be valid;
1605                          * please remove assertion, or add legal values
1606                          * to either block */
1607                         assert( 0 );
1608                         break;
1609                 }
1610
1611                 return 1;
1612         }
1613
1614         if (c->op == SLAP_CONFIG_EMIT) {
1615                 if ( c->be->be_suffix == NULL
1616                                 || BER_BVISNULL( &c->be->be_suffix[0] ) )
1617                 {
1618                         return 1;
1619                 } else {
1620                         value_add( &c->rvalue_vals, c->be->be_suffix );
1621                         value_add( &c->rvalue_nvals, c->be->be_nsuffix );
1622                         return 0;
1623                 }
1624         } else if ( c->op == LDAP_MOD_DELETE ) {
1625                 if ( c->valx < 0 ) {
1626                         ber_bvarray_free( c->be->be_suffix );
1627                         ber_bvarray_free( c->be->be_nsuffix );
1628                         c->be->be_suffix = NULL;
1629                         c->be->be_nsuffix = NULL;
1630                 } else {
1631                         int i = c->valx;
1632                         ch_free( c->be->be_suffix[i].bv_val );
1633                         ch_free( c->be->be_nsuffix[i].bv_val );
1634                         for (; c->be->be_suffix[i].bv_val; i++) {
1635                                 c->be->be_suffix[i] = c->be->be_suffix[i+1];
1636                                 c->be->be_nsuffix[i] = c->be->be_nsuffix[i+1];
1637                         }
1638                 }
1639                 return 0;
1640         }
1641
1642 #ifdef SLAPD_MONITOR_DN
1643         if(!strcasecmp(c->argv[1], SLAPD_MONITOR_DN)) {
1644                 sprintf( c->msg, "<%s> DN is reserved for monitoring slapd",
1645                         c->argv[0] );
1646                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1647                         c->log, c->msg, SLAPD_MONITOR_DN);
1648                 return(1);
1649         }
1650 #endif
1651
1652         pdn = c->value_dn;
1653         ndn = c->value_ndn;
1654         tbe = select_backend(&ndn, 0, 0);
1655         if(tbe == c->be) {
1656                 Debug( SLAPD_DEBUG_CONFIG_ERROR,
1657                         "%s: suffix already served by this backend!"
1658                         SLAPD_CONF_UNKNOWN_IGNORED ".\n",
1659                         c->log, 0, 0);
1660 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
1661                 return 1;
1662 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
1663                 free(pdn.bv_val);
1664                 free(ndn.bv_val);
1665         } else if(tbe) {
1666                 char    *type = tbe->bd_info->bi_type;
1667
1668                 if ( overlay_is_over( tbe ) ) {
1669                         slap_overinfo   *oi = (slap_overinfo *)tbe->bd_info->bi_private;
1670                         type = oi->oi_orig->bi_type;
1671                 }
1672
1673                 sprintf( c->msg, "<%s> namingContext \"%s\" already served by "
1674                         "a preceding %s database serving namingContext",
1675                         c->argv[0], pdn.bv_val, type );
1676                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1677                         c->log, c->msg, tbe->be_suffix[0].bv_val);
1678                 free(pdn.bv_val);
1679                 free(ndn.bv_val);
1680                 return(1);
1681         } else if(pdn.bv_len == 0 && default_search_nbase.bv_len) {
1682                 Debug(LDAP_DEBUG_ANY, "%s: suffix DN empty and default search "
1683                         "base provided \"%s\" (assuming okay)\n",
1684                         c->log, default_search_base.bv_val, 0);
1685         }
1686         ber_bvarray_add(&c->be->be_suffix, &pdn);
1687         ber_bvarray_add(&c->be->be_nsuffix, &ndn);
1688         return(0);
1689 }
1690
1691 static int
1692 config_rootdn(ConfigArgs *c) {
1693         if (c->op == SLAP_CONFIG_EMIT) {
1694                 if ( !BER_BVISNULL( &c->be->be_rootdn )) {
1695                         value_add_one(&c->rvalue_vals, &c->be->be_rootdn);
1696                         value_add_one(&c->rvalue_nvals, &c->be->be_rootndn);
1697                         return 0;
1698                 } else {
1699                         return 1;
1700                 }
1701         } else if ( c->op == LDAP_MOD_DELETE ) {
1702                 ch_free( c->be->be_rootdn.bv_val );
1703                 ch_free( c->be->be_rootndn.bv_val );
1704                 BER_BVZERO( &c->be->be_rootdn );
1705                 BER_BVZERO( &c->be->be_rootndn );
1706                 return 0;
1707         }
1708         if ( !BER_BVISNULL( &c->be->be_rootdn )) {
1709                 ch_free( c->be->be_rootdn.bv_val );
1710                 ch_free( c->be->be_rootndn.bv_val );
1711         }
1712         c->be->be_rootdn = c->value_dn;
1713         c->be->be_rootndn = c->value_ndn;
1714         return(0);
1715 }
1716
1717 static int
1718 config_rootpw(ConfigArgs *c) {
1719         Backend *tbe;
1720
1721         if (c->op == SLAP_CONFIG_EMIT) {
1722                 if (!BER_BVISEMPTY(&c->be->be_rootpw)) {
1723                         /* don't copy, because "rootpw" is marked
1724                          * as CFG_BERVAL */
1725                         c->value_bv = c->be->be_rootpw;
1726                         return 0;
1727                 }
1728                 return 1;
1729         } else if ( c->op == LDAP_MOD_DELETE ) {
1730                 ch_free( c->be->be_rootpw.bv_val );
1731                 BER_BVZERO( &c->be->be_rootpw );
1732                 return 0;
1733         }
1734
1735         tbe = select_backend(&c->be->be_rootndn, 0, 0);
1736         if(tbe != c->be) {
1737                 sprintf( c->msg, "<%s> can only be set when rootdn is under suffix",
1738                         c->argv[0] );
1739                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1740                         c->log, c->msg, 0);
1741                 return(1);
1742         }
1743         if ( !BER_BVISNULL( &c->be->be_rootpw ))
1744                 ch_free( c->be->be_rootpw.bv_val );
1745         c->be->be_rootpw = c->value_bv;
1746         return(0);
1747 }
1748
1749 static int
1750 config_restrict(ConfigArgs *c) {
1751         slap_mask_t restrictops = 0;
1752         int i;
1753         slap_verbmasks restrictable_ops[] = {
1754                 { BER_BVC("bind"),              SLAP_RESTRICT_OP_BIND },
1755                 { BER_BVC("add"),               SLAP_RESTRICT_OP_ADD },
1756                 { BER_BVC("modify"),            SLAP_RESTRICT_OP_MODIFY },
1757                 { BER_BVC("rename"),            SLAP_RESTRICT_OP_RENAME },
1758                 { BER_BVC("modrdn"),            0 },
1759                 { BER_BVC("delete"),            SLAP_RESTRICT_OP_DELETE },
1760                 { BER_BVC("search"),            SLAP_RESTRICT_OP_SEARCH },
1761                 { BER_BVC("compare"),   SLAP_RESTRICT_OP_COMPARE },
1762                 { BER_BVC("read"),              SLAP_RESTRICT_OP_READS },
1763                 { BER_BVC("write"),             SLAP_RESTRICT_OP_WRITES },
1764                 { BER_BVC("extended"),  SLAP_RESTRICT_OP_EXTENDED },
1765                 { BER_BVC("extended=" LDAP_EXOP_START_TLS ),            SLAP_RESTRICT_EXOP_START_TLS },
1766                 { BER_BVC("extended=" LDAP_EXOP_MODIFY_PASSWD ),        SLAP_RESTRICT_EXOP_MODIFY_PASSWD },
1767                 { BER_BVC("extended=" LDAP_EXOP_X_WHO_AM_I ),           SLAP_RESTRICT_EXOP_WHOAMI },
1768                 { BER_BVC("extended=" LDAP_EXOP_X_CANCEL ),             SLAP_RESTRICT_EXOP_CANCEL },
1769                 { BER_BVNULL,   0 }
1770         };
1771
1772         if (c->op == SLAP_CONFIG_EMIT) {
1773                 return mask_to_verbs( restrictable_ops, c->be->be_restrictops,
1774                         &c->rvalue_vals );
1775         } else if ( c->op == LDAP_MOD_DELETE ) {
1776                 if ( !c->line ) {
1777                         c->be->be_restrictops = 0;
1778                 } else {
1779                         restrictops = verb_to_mask( c->line, restrictable_ops );
1780                         c->be->be_restrictops ^= restrictops;
1781                 }
1782                 return 0;
1783         }
1784         i = verbs_to_mask( c->argc, c->argv, restrictable_ops, &restrictops );
1785         if ( i ) {
1786                 sprintf( c->msg, "<%s> unknown operation", c->argv[0] );
1787                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1788                         c->log, c->msg, c->argv[i]);
1789                 return(1);
1790         }
1791         if ( restrictops & SLAP_RESTRICT_OP_EXTENDED )
1792                 restrictops &= ~SLAP_RESTRICT_EXOP_MASK;
1793         c->be->be_restrictops |= restrictops;
1794         return(0);
1795 }
1796
1797 static int
1798 config_allows(ConfigArgs *c) {
1799         slap_mask_t allows = 0;
1800         int i;
1801         slap_verbmasks allowable_ops[] = {
1802                 { BER_BVC("bind_v2"),           SLAP_ALLOW_BIND_V2 },
1803                 { BER_BVC("bind_anon_cred"),    SLAP_ALLOW_BIND_ANON_CRED },
1804                 { BER_BVC("bind_anon_dn"),      SLAP_ALLOW_BIND_ANON_DN },
1805                 { BER_BVC("update_anon"),       SLAP_ALLOW_UPDATE_ANON },
1806                 { BER_BVNULL,   0 }
1807         };
1808         if (c->op == SLAP_CONFIG_EMIT) {
1809                 return mask_to_verbs( allowable_ops, global_allows, &c->rvalue_vals );
1810         } else if ( c->op == LDAP_MOD_DELETE ) {
1811                 if ( !c->line ) {
1812                         global_allows = 0;
1813                 } else {
1814                         allows = verb_to_mask( c->line, allowable_ops );
1815                         global_allows ^= allows;
1816                 }
1817                 return 0;
1818         }
1819         i = verbs_to_mask(c->argc, c->argv, allowable_ops, &allows);
1820         if ( i ) {
1821                 sprintf( c->msg, "<%s> unknown feature", c->argv[0] );
1822                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1823                         c->log, c->msg, c->argv[i]);
1824                 return(1);
1825         }
1826         global_allows |= allows;
1827         return(0);
1828 }
1829
1830 static int
1831 config_disallows(ConfigArgs *c) {
1832         slap_mask_t disallows = 0;
1833         int i;
1834         slap_verbmasks disallowable_ops[] = {
1835                 { BER_BVC("bind_anon"),         SLAP_DISALLOW_BIND_ANON },
1836                 { BER_BVC("bind_simple"),       SLAP_DISALLOW_BIND_SIMPLE },
1837                 { BER_BVC("bind_krb4"),         SLAP_DISALLOW_BIND_KRBV4 },
1838                 { BER_BVC("tls_2_anon"),                SLAP_DISALLOW_TLS_2_ANON },
1839                 { BER_BVC("tls_authc"),         SLAP_DISALLOW_TLS_AUTHC },
1840                 { BER_BVNULL, 0 }
1841         };
1842         if (c->op == SLAP_CONFIG_EMIT) {
1843                 return mask_to_verbs( disallowable_ops, global_disallows, &c->rvalue_vals );
1844         } else if ( c->op == LDAP_MOD_DELETE ) {
1845                 if ( !c->line ) {
1846                         global_disallows = 0;
1847                 } else {
1848                         disallows = verb_to_mask( c->line, disallowable_ops );
1849                         global_disallows ^= disallows;
1850                 }
1851                 return 0;
1852         }
1853         i = verbs_to_mask(c->argc, c->argv, disallowable_ops, &disallows);
1854         if ( i ) {
1855                 sprintf( c->msg, "<%s> unknown feature", c->argv[0] );
1856                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1857                         c->log, c->msg, c->argv[i]);
1858                 return(1);
1859         }
1860         global_disallows |= disallows;
1861         return(0);
1862 }
1863
1864 static int
1865 config_requires(ConfigArgs *c) {
1866         slap_mask_t requires = 0;
1867         int i;
1868         slap_verbmasks requires_ops[] = {
1869                 { BER_BVC("bind"),              SLAP_REQUIRE_BIND },
1870                 { BER_BVC("LDAPv3"),            SLAP_REQUIRE_LDAP_V3 },
1871                 { BER_BVC("authc"),             SLAP_REQUIRE_AUTHC },
1872                 { BER_BVC("sasl"),              SLAP_REQUIRE_SASL },
1873                 { BER_BVC("strong"),            SLAP_REQUIRE_STRONG },
1874                 { BER_BVNULL, 0 }
1875         };
1876         if (c->op == SLAP_CONFIG_EMIT) {
1877                 return mask_to_verbs( requires_ops, c->be->be_requires, &c->rvalue_vals );
1878         } else if ( c->op == LDAP_MOD_DELETE ) {
1879                 if ( !c->line ) {
1880                         c->be->be_requires = 0;
1881                 } else {
1882                         requires = verb_to_mask( c->line, requires_ops );
1883                         c->be->be_requires ^= requires;
1884                 }
1885                 return 0;
1886         }
1887         i = verbs_to_mask(c->argc, c->argv, requires_ops, &requires);
1888         if ( i ) {
1889                 sprintf( c->msg, "<%s> unknown feature", c->argv[0] );
1890                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1891                         c->log, c->msg, c->argv[i]);
1892                 return(1);
1893         }
1894         c->be->be_requires = requires;
1895         return(0);
1896 }
1897
1898 static slap_verbmasks   *loglevel_ops;
1899
1900 static int
1901 loglevel_init( void )
1902 {
1903         slap_verbmasks  lo[] = {
1904                 { BER_BVC("Any"),       -1 },
1905                 { BER_BVC("Trace"),     LDAP_DEBUG_TRACE },
1906                 { BER_BVC("Packets"),   LDAP_DEBUG_PACKETS },
1907                 { BER_BVC("Args"),      LDAP_DEBUG_ARGS },
1908                 { BER_BVC("Conns"),     LDAP_DEBUG_CONNS },
1909                 { BER_BVC("BER"),       LDAP_DEBUG_BER },
1910                 { BER_BVC("Filter"),    LDAP_DEBUG_FILTER },
1911                 { BER_BVC("Config"),    LDAP_DEBUG_CONFIG },
1912                 { BER_BVC("ACL"),       LDAP_DEBUG_ACL },
1913                 { BER_BVC("Stats"),     LDAP_DEBUG_STATS },
1914                 { BER_BVC("Stats2"),    LDAP_DEBUG_STATS2 },
1915                 { BER_BVC("Shell"),     LDAP_DEBUG_SHELL },
1916                 { BER_BVC("Parse"),     LDAP_DEBUG_PARSE },
1917                 { BER_BVC("Cache"),     LDAP_DEBUG_CACHE },
1918                 { BER_BVC("Index"),     LDAP_DEBUG_INDEX },
1919                 { BER_BVC("Sync"),      LDAP_DEBUG_SYNC },
1920                 { BER_BVNULL,   0 }
1921         };
1922
1923         return slap_verbmasks_init( &loglevel_ops, lo );
1924 }
1925
1926 static void
1927 loglevel_destroy( void )
1928 {
1929         if ( loglevel_ops ) {
1930                 (void)slap_verbmasks_destroy( loglevel_ops );
1931         }
1932         loglevel_ops = NULL;
1933 }
1934
1935 static slap_mask_t      loglevel_ignore[] = { -1, 0 };
1936
1937 int
1938 slap_loglevel_register( slap_mask_t m, struct berval *s )
1939 {
1940         int     rc;
1941
1942         if ( loglevel_ops == NULL ) {
1943                 loglevel_init();
1944         }
1945
1946         rc = slap_verbmasks_append( &loglevel_ops, m, s, loglevel_ignore );
1947
1948         if ( rc != 0 ) {
1949                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_register(%lu, \"%s\") failed\n",
1950                         m, s->bv_val, 0 );
1951         }
1952
1953         return rc;
1954 }
1955
1956 int
1957 str2loglevel( const char *s, int *l )
1958 {
1959         int     i;
1960
1961         if ( loglevel_ops == NULL ) {
1962                 loglevel_init();
1963         }
1964
1965         i = verb_to_mask( s, loglevel_ops );
1966
1967         if ( BER_BVISNULL( &loglevel_ops[ i ].word) ) {
1968                 return -1;
1969         }
1970
1971         *l = loglevel_ops[ i ].mask;
1972
1973         return 0;
1974 }
1975
1976 static int config_syslog;
1977
1978 static int
1979 config_loglevel(ConfigArgs *c) {
1980         int i;
1981         char *next;
1982
1983         if ( loglevel_ops == NULL ) {
1984                 loglevel_init();
1985         }
1986
1987         if (c->op == SLAP_CONFIG_EMIT) {
1988                 /* Get default or commandline slapd setting */
1989                 if ( ldap_syslog && !config_syslog )
1990                         config_syslog = ldap_syslog;
1991                 return mask_to_verbs( loglevel_ops, config_syslog, &c->rvalue_vals );
1992         } else if ( c->op == LDAP_MOD_DELETE ) {
1993                 if ( !c->line ) {
1994                         config_syslog = 0;
1995                 } else {
1996                         int level = verb_to_mask( c->line, loglevel_ops );
1997                         config_syslog ^= level;
1998                 }
1999                 if ( slapMode & SLAP_SERVER_MODE ) {
2000                         ldap_syslog = config_syslog;
2001                 }
2002                 return 0;
2003         }
2004
2005         config_syslog = 0;
2006
2007         for( i=1; i < c->argc; i++ ) {
2008                 int     level;
2009
2010                 if ( isdigit( c->argv[i][0] ) || c->argv[i][0] == '-' ) {
2011                         level = strtol( c->argv[i], &next, 10 );
2012                         if ( next == NULL || next[0] != '\0' ) {
2013                                 sprintf( c->msg, "<%s> unable to parse level", c->argv[0] );
2014                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2015                                         c->log, c->msg, c->argv[i]);
2016                                 return( 1 );
2017                         }
2018                 } else {
2019                         if ( str2loglevel( c->argv[i], &level ) ) {
2020                                 sprintf( c->msg, "<%s> unknown level", c->argv[0] );
2021                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2022                                         c->log, c->msg, c->argv[i]);
2023                                 return( 1 );
2024                         }
2025                 }
2026                 config_syslog |= level;
2027         }
2028         if ( slapMode & SLAP_SERVER_MODE ) {
2029                 ldap_syslog = config_syslog;
2030         }
2031         return(0);
2032 }
2033
2034 static int
2035 config_referral(ConfigArgs *c) {
2036         struct berval val;
2037         if (c->op == SLAP_CONFIG_EMIT) {
2038                 if ( default_referral ) {
2039                         value_add( &c->rvalue_vals, default_referral );
2040                         return 0;
2041                 } else {
2042                         return 1;
2043                 }
2044         } else if ( c->op == LDAP_MOD_DELETE ) {
2045                 if ( c->valx < 0 ) {
2046                         ber_bvarray_free( default_referral );
2047                         default_referral = NULL;
2048                 } else {
2049                         int i = c->valx;
2050                         ch_free( default_referral[i].bv_val );
2051                         for (; default_referral[i].bv_val; i++ )
2052                                 default_referral[i] = default_referral[i+1];
2053                 }
2054                 return 0;
2055         }
2056         if(validate_global_referral(c->argv[1])) {
2057                 sprintf( c->msg, "<%s> invalid URL", c->argv[0] );
2058                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2059                         c->log, c->msg, c->argv[1]);
2060                 return(1);
2061         }
2062
2063         ber_str2bv(c->argv[1], 0, 0, &val);
2064         if(value_add_one(&default_referral, &val)) return(LDAP_OTHER);
2065         return(0);
2066 }
2067
2068 static struct {
2069         struct berval key;
2070         int off;
2071 } sec_keys[] = {
2072         { BER_BVC("ssf="), offsetof(slap_ssf_set_t, sss_ssf) },
2073         { BER_BVC("transport="), offsetof(slap_ssf_set_t, sss_transport) },
2074         { BER_BVC("tls="), offsetof(slap_ssf_set_t, sss_tls) },
2075         { BER_BVC("sasl="), offsetof(slap_ssf_set_t, sss_sasl) },
2076         { BER_BVC("update_ssf="), offsetof(slap_ssf_set_t, sss_update_ssf) },
2077         { BER_BVC("update_transport="), offsetof(slap_ssf_set_t, sss_update_transport) },
2078         { BER_BVC("update_tls="), offsetof(slap_ssf_set_t, sss_update_tls) },
2079         { BER_BVC("update_sasl="), offsetof(slap_ssf_set_t, sss_update_sasl) },
2080         { BER_BVC("simple_bind="), offsetof(slap_ssf_set_t, sss_simple_bind) },
2081         { BER_BVNULL, 0 }
2082 };
2083
2084 static int
2085 config_security(ConfigArgs *c) {
2086         slap_ssf_set_t *set = &c->be->be_ssf_set;
2087         char *next;
2088         int i, j;
2089         if (c->op == SLAP_CONFIG_EMIT) {
2090                 char numbuf[32];
2091                 struct berval bv;
2092                 slap_ssf_t *tgt;
2093                 int rc = 1;
2094
2095                 for (i=0; !BER_BVISNULL( &sec_keys[i].key ); i++) {
2096                         tgt = (slap_ssf_t *)((char *)set + sec_keys[i].off);
2097                         if ( *tgt ) {
2098                                 rc = 0;
2099                                 bv.bv_len = sprintf( numbuf, "%u", *tgt );
2100                                 bv.bv_len += sec_keys[i].key.bv_len;
2101                                 bv.bv_val = ch_malloc( bv.bv_len + 1);
2102                                 next = lutil_strcopy( bv.bv_val, sec_keys[i].key.bv_val );
2103                                 strcpy( next, numbuf );
2104                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2105                         }
2106                 }
2107                 return rc;
2108         }
2109         for(i = 1; i < c->argc; i++) {
2110                 slap_ssf_t *tgt = NULL;
2111                 char *src;
2112                 for ( j=0; !BER_BVISNULL( &sec_keys[j].key ); j++ ) {
2113                         if(!strncasecmp(c->argv[i], sec_keys[j].key.bv_val,
2114                                 sec_keys[j].key.bv_len)) {
2115                                 src = c->argv[i] + sec_keys[j].key.bv_len;
2116                                 tgt = (slap_ssf_t *)((char *)set + sec_keys[j].off);
2117                                 break;
2118                         }
2119                 }
2120                 if ( !tgt ) {
2121                         sprintf( c->msg, "<%s> unknown factor", c->argv[0] );
2122                         Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2123                                 c->log, c->msg, c->argv[i]);
2124                         return(1);
2125                 }
2126
2127                 *tgt = strtol(src, &next, 10);
2128                 if(next == NULL || next[0] != '\0' ) {
2129                         sprintf( c->msg, "<%s> unable to parse factor", c->argv[0] );
2130                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2131                                 c->log, c->msg, c->argv[i]);
2132                         return(1);
2133                 }
2134         }
2135         return(0);
2136 }
2137
2138 char *
2139 anlist_unparse( AttributeName *an, char *ptr ) {
2140         int comma = 0;
2141
2142         for (; !BER_BVISNULL( &an->an_name ); an++) {
2143                 if ( comma ) *ptr++ = ',';
2144                 ptr = lutil_strcopy( ptr, an->an_name.bv_val );
2145                 comma = 1;
2146         }
2147         return ptr;
2148 }
2149
2150 static void
2151 replica_unparse( struct slap_replica_info *ri, int i, struct berval *bv )
2152 {
2153         int len;
2154         char *ptr;
2155         struct berval bc = BER_BVNULL;
2156         char numbuf[32];
2157
2158         len = sprintf(numbuf, IFMT, i );
2159
2160         len += strlen( ri->ri_uri ) + STRLENOF("uri=");
2161         if ( ri->ri_nsuffix ) {
2162                 for (i=0; !BER_BVISNULL( &ri->ri_nsuffix[i] ); i++) {
2163                         len += ri->ri_nsuffix[i].bv_len + STRLENOF(" suffix=\"\"");
2164                 }
2165         }
2166         if ( ri->ri_attrs ) {
2167                 len += STRLENOF("attr");
2168                 if ( ri->ri_exclude ) len++;
2169                 for (i=0; !BER_BVISNULL( &ri->ri_attrs[i].an_name ); i++) {
2170                         len += 1 + ri->ri_attrs[i].an_name.bv_len;
2171                 }
2172         }
2173         bindconf_unparse( &ri->ri_bindconf, &bc );
2174         len += bc.bv_len;
2175
2176         bv->bv_val = ch_malloc(len + 1);
2177         bv->bv_len = len;
2178
2179         ptr = lutil_strcopy( bv->bv_val, numbuf );
2180         ptr = lutil_strcopy( ptr, "uri=" );
2181         ptr = lutil_strcopy( ptr, ri->ri_uri );
2182
2183         if ( ri->ri_nsuffix ) {
2184                 for (i=0; !BER_BVISNULL( &ri->ri_nsuffix[i] ); i++) {
2185                         ptr = lutil_strcopy( ptr, " suffix=\"" );
2186                         ptr = lutil_strcopy( ptr, ri->ri_nsuffix[i].bv_val );
2187                         *ptr++ = '"';
2188                 }
2189         }
2190         if ( ri->ri_attrs ) {
2191                 ptr = lutil_strcopy( ptr, "attr" );
2192                 if ( ri->ri_exclude ) *ptr++ = '!';
2193                 *ptr++ = '=';
2194                 ptr = anlist_unparse( ri->ri_attrs, ptr );
2195         }
2196         if ( bc.bv_val ) {
2197                 strcpy( ptr, bc.bv_val );
2198                 ch_free( bc.bv_val );
2199         }
2200 }
2201
2202 static int
2203 config_replica(ConfigArgs *c) {
2204         int i, nr = -1, len;
2205         char *replicahost, *replicauri;
2206         LDAPURLDesc *ludp;
2207
2208         if (c->op == SLAP_CONFIG_EMIT) {
2209                 if (c->be->be_replica) {
2210                         struct berval bv;
2211                         for (i=0;c->be->be_replica[i]; i++) {
2212                                 replica_unparse( c->be->be_replica[i], i, &bv );
2213                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2214                         }
2215                         return 0;
2216                 }
2217                 return 1;
2218         } else if ( c->op == LDAP_MOD_DELETE ) {
2219                 /* FIXME: there is no replica_free function */
2220                 if ( c->valx < 0 ) {
2221                 } else {
2222                 }
2223         }
2224         if(SLAP_MONITOR(c->be)) {
2225                 Debug(LDAP_DEBUG_ANY, "%s: "
2226                         "\"replica\" should not be used inside monitor database\n",
2227                         c->log, 0, 0);
2228                 return(0);      /* FIXME: should this be an error? */
2229         }
2230
2231         for(i = 1; i < c->argc; i++) {
2232                 if(!strncasecmp(c->argv[i], "host=", STRLENOF("host="))) {
2233                         replicahost = c->argv[i] + STRLENOF("host=");
2234                         len = strlen( replicahost );
2235                         replicauri = ch_malloc( len + STRLENOF("ldap://") + 1 );
2236                         sprintf( replicauri, "ldap://%s", replicahost );
2237                         replicahost = replicauri + STRLENOF( "ldap://");
2238                         nr = add_replica_info(c->be, replicauri, replicahost);
2239                         break;
2240                 } else if(!strncasecmp(c->argv[i], "uri=", STRLENOF("uri="))) {
2241                         if(ldap_url_parse(c->argv[i] + STRLENOF("uri="), &ludp) != LDAP_SUCCESS) {
2242                                 sprintf( c->msg, "<%s> invalid uri", c->argv[0] );
2243                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
2244                                 return(1);
2245                         }
2246                         if(!ludp->lud_host) {
2247                                 ldap_free_urldesc(ludp);
2248                                 sprintf( c->msg, "<%s> invalid uri - missing hostname",
2249                                         c->argv[0] );
2250                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
2251                                 return(1);
2252                         }
2253                         ldap_free_urldesc(ludp);
2254                         replicauri = c->argv[i] + STRLENOF("uri=");
2255                         replicauri = ch_strdup( replicauri );
2256                         replicahost = strchr( replicauri, '/' );
2257                         replicahost += 2;
2258                         nr = add_replica_info(c->be, replicauri, replicahost);
2259                         break;
2260                 }
2261         }
2262         if(i == c->argc) {
2263                 sprintf( c->msg, "<%s> missing host or uri", c->argv[0] );
2264                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->msg, 0 );
2265                 return(1);
2266         } else if(nr == -1) {
2267                 sprintf( c->msg, "<%s> unable to add replica", c->argv[0] );
2268                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n", c->log, c->msg, replicauri );
2269                 return(1);
2270         } else {
2271                 for(i = 1; i < c->argc; i++) {
2272                         if(!strncasecmp(c->argv[i], "suffix=", STRLENOF( "suffix="))) {
2273                                 switch(add_replica_suffix(c->be, nr, c->argv[i] + STRLENOF("suffix="))) {
2274                                         case 1:
2275                                                 Debug( SLAPD_DEBUG_CONFIG_ERROR, "%s: "
2276                                                 "suffix \"%s\" in \"replica\" line is not valid for backend"
2277                                                 SLAPD_CONF_UNKNOWN_IGNORED ".\n",
2278                                                 c->log, c->argv[i] + STRLENOF("suffix="), 0);
2279 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
2280                                                 return 1;
2281 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
2282                                                 break;
2283                                         case 2:
2284                                                 Debug( SLAPD_DEBUG_CONFIG_ERROR, "%s: "
2285                                                 "unable to normalize suffix in \"replica\" line"
2286                                                 SLAPD_CONF_UNKNOWN_IGNORED ".\n",
2287                                                 c->log, 0, 0);
2288 #ifdef SLAPD_CONF_UNKNOWN_BAILOUT
2289                                                 return 1;
2290 #endif /* SLAPD_CONF_UNKNOWN_BAILOUT */
2291                                                 break;
2292                                 }
2293
2294                         } else if(!strncasecmp(c->argv[i], "attr", STRLENOF("attr"))) {
2295                                 int exclude = 0;
2296                                 char *arg = c->argv[i] + STRLENOF("attr");
2297                                 if(arg[0] == '!') {
2298                                         arg++;
2299                                         exclude = 1;
2300                                 }
2301                                 if(arg[0] != '=') {
2302                                         continue;
2303                                 }
2304                                 if(add_replica_attrs(c->be, nr, arg + 1, exclude)) {
2305                                         sprintf( c->msg, "<%s> unknown attribute", c->argv[0] );
2306                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2307                                                 c->log, c->msg, arg + 1);
2308                                         return(1);
2309                                 }
2310                         } else if ( bindconf_parse( c->argv[i],
2311                                         &c->be->be_replica[nr]->ri_bindconf ) ) {
2312                                 return(1);
2313                         }
2314                 }
2315         }
2316         return(0);
2317 }
2318
2319 static int
2320 config_updatedn(ConfigArgs *c) {
2321         if (c->op == SLAP_CONFIG_EMIT) {
2322                 if (!BER_BVISEMPTY(&c->be->be_update_ndn)) {
2323                         value_add_one(&c->rvalue_vals, &c->be->be_update_ndn);
2324                         value_add_one(&c->rvalue_nvals, &c->be->be_update_ndn);
2325                         return 0;
2326                 }
2327                 return 1;
2328         } else if ( c->op == LDAP_MOD_DELETE ) {
2329                 ch_free( c->be->be_update_ndn.bv_val );
2330                 BER_BVZERO( &c->be->be_update_ndn );
2331                 SLAP_DBFLAGS(c->be) ^= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SLURP_SHADOW);
2332                 return 0;
2333         }
2334         if(SLAP_SHADOW(c->be)) {
2335                 sprintf( c->msg, "<%s> database already shadowed", c->argv[0] );
2336                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2337                         c->log, c->msg, 0);
2338                 return(1);
2339         }
2340
2341         ber_memfree_x( c->value_dn.bv_val, NULL );
2342         if ( !BER_BVISNULL( &c->be->be_update_ndn ) ) {
2343                 ber_memfree_x( c->be->be_update_ndn.bv_val, NULL );
2344         }
2345         c->be->be_update_ndn = c->value_ndn;
2346         BER_BVZERO( &c->value_dn );
2347         BER_BVZERO( &c->value_ndn );
2348
2349         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SLURP_SHADOW);
2350         return(0);
2351 }
2352
2353 static int
2354 config_updateref(ConfigArgs *c) {
2355         struct berval val;
2356         if (c->op == SLAP_CONFIG_EMIT) {
2357                 if ( c->be->be_update_refs ) {
2358                         value_add( &c->rvalue_vals, c->be->be_update_refs );
2359                         return 0;
2360                 } else {
2361                         return 1;
2362                 }
2363         } else if ( c->op == LDAP_MOD_DELETE ) {
2364                 if ( c->valx < 0 ) {
2365                         ber_bvarray_free( c->be->be_update_refs );
2366                         c->be->be_update_refs = NULL;
2367                 } else {
2368                         int i = c->valx;
2369                         ch_free( c->be->be_update_refs[i].bv_val );
2370                         for (; c->be->be_update_refs[i].bv_val; i++)
2371                                 c->be->be_update_refs[i] = c->be->be_update_refs[i+1];
2372                 }
2373                 return 0;
2374         }
2375         if(!SLAP_SHADOW(c->be)) {
2376                 sprintf( c->msg, "<%s> must appear after syncrepl or updatedn",
2377                         c->argv[0] );
2378                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2379                         c->log, c->msg, 0);
2380                 return(1);
2381         }
2382
2383         if(validate_global_referral(c->argv[1])) {
2384                 sprintf( c->msg, "<%s> invalid URL", c->argv[0] );
2385                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2386                         c->log, c->msg, c->argv[1]);
2387                 return(1);
2388         }
2389         ber_str2bv(c->argv[1], 0, 0, &val);
2390         if(value_add_one(&c->be->be_update_refs, &val)) return(LDAP_OTHER);
2391         return(0);
2392 }
2393
2394 static int
2395 config_include(ConfigArgs *c) {
2396         int savelineno = c->lineno;
2397         int rc;
2398         ConfigFile *cf;
2399         ConfigFile *cfsave = cfn;
2400         ConfigFile *cf2 = NULL;
2401         if (c->op == SLAP_CONFIG_EMIT) {
2402                 if (c->private) {
2403                         ConfigFile *cf = c->private;
2404                         value_add_one( &c->rvalue_vals, &cf->c_file );
2405                         return 0;
2406                 }
2407                 return 1;
2408         } else if ( c->op == LDAP_MOD_DELETE ) {
2409         }
2410         cf = ch_calloc( 1, sizeof(ConfigFile));
2411         if ( cfn->c_kids ) {
2412                 for (cf2=cfn->c_kids; cf2 && cf2->c_sibs; cf2=cf2->c_sibs) ;
2413                 cf2->c_sibs = cf;
2414         } else {
2415                 cfn->c_kids = cf;
2416         }
2417         cfn = cf;
2418         ber_str2bv( c->argv[1], 0, 1, &cf->c_file );
2419         rc = read_config_file(c->argv[1], c->depth + 1, c, config_back_cf_table);
2420         c->lineno = savelineno - 1;
2421         cfn = cfsave;
2422         if ( rc ) {
2423                 if ( cf2 ) cf2->c_sibs = NULL;
2424                 else cfn->c_kids = NULL;
2425                 ch_free( cf->c_file.bv_val );
2426                 ch_free( cf );
2427         } else {
2428                 c->private = cf;
2429         }
2430         return(rc);
2431 }
2432
2433 #ifdef HAVE_TLS
2434 static int
2435 config_tls_option(ConfigArgs *c) {
2436         int flag;
2437         switch(c->type) {
2438         case CFG_TLS_RAND:      flag = LDAP_OPT_X_TLS_RANDOM_FILE;      break;
2439         case CFG_TLS_CIPHER:    flag = LDAP_OPT_X_TLS_CIPHER_SUITE;     break;
2440         case CFG_TLS_CERT_FILE: flag = LDAP_OPT_X_TLS_CERTFILE;         break;  
2441         case CFG_TLS_CERT_KEY:  flag = LDAP_OPT_X_TLS_KEYFILE;          break;
2442         case CFG_TLS_CA_PATH:   flag = LDAP_OPT_X_TLS_CACERTDIR;        break;
2443         case CFG_TLS_CA_FILE:   flag = LDAP_OPT_X_TLS_CACERTFILE;       break;
2444         default:                Debug(LDAP_DEBUG_ANY, "%s: "
2445                                         "unknown tls_option <0x%x>\n",
2446                                         c->log, c->type, 0);
2447         }
2448         if (c->op == SLAP_CONFIG_EMIT) {
2449                 return ldap_pvt_tls_get_option( NULL, flag, &c->value_string );
2450         } else if ( c->op == LDAP_MOD_DELETE ) {
2451                 return ldap_pvt_tls_set_option( NULL, flag, NULL );
2452         }
2453         ch_free(c->value_string);
2454         return(ldap_pvt_tls_set_option(NULL, flag, c->argv[1]));
2455 }
2456
2457 /* FIXME: this ought to be provided by libldap */
2458 static int
2459 config_tls_config(ConfigArgs *c) {
2460         int i, flag;
2461         slap_verbmasks crlkeys[] = {
2462                 { BER_BVC("none"),      LDAP_OPT_X_TLS_CRL_NONE },
2463                 { BER_BVC("peer"),      LDAP_OPT_X_TLS_CRL_PEER },
2464                 { BER_BVC("all"),       LDAP_OPT_X_TLS_CRL_ALL },
2465                 { BER_BVNULL, 0 }
2466         };
2467         slap_verbmasks vfykeys[] = {
2468                 { BER_BVC("never"),     LDAP_OPT_X_TLS_NEVER },
2469                 { BER_BVC("demand"),    LDAP_OPT_X_TLS_DEMAND },
2470                 { BER_BVC("try"),       LDAP_OPT_X_TLS_TRY },
2471                 { BER_BVC("hard"),      LDAP_OPT_X_TLS_HARD },
2472                 { BER_BVNULL, 0 }
2473         }, *keys;
2474         switch(c->type) {
2475         case CFG_TLS_CRLCHECK:  flag = LDAP_OPT_X_TLS_CRLCHECK;         keys = crlkeys; break;
2476         case CFG_TLS_VERIFY:    flag = LDAP_OPT_X_TLS_REQUIRE_CERT;     keys = vfykeys; break;
2477         default:
2478                 Debug(LDAP_DEBUG_ANY, "%s: "
2479                                 "unknown tls_option <0x%x>\n",
2480                                 c->log, c->type, 0);
2481         }
2482         if (c->op == SLAP_CONFIG_EMIT) {
2483                 ldap_pvt_tls_get_option( NULL, flag, &c->value_int );
2484                 for (i=0; !BER_BVISNULL(&keys[i].word); i++) {
2485                         if (keys[i].mask == c->value_int) {
2486                                 c->value_string = ch_strdup( keys[i].word.bv_val );
2487                                 return 0;
2488                         }
2489                 }
2490                 return 1;
2491         } else if ( c->op == LDAP_MOD_DELETE ) {
2492                 int i = 0;
2493                 return ldap_pvt_tls_set_option( NULL, flag, &i );
2494         }
2495         ch_free( c->value_string );
2496         if(isdigit((unsigned char)c->argv[1][0])) {
2497                 i = atoi(c->argv[1]);
2498                 return(ldap_pvt_tls_set_option(NULL, flag, &i));
2499         } else {
2500                 return(ldap_int_tls_config(NULL, flag, c->argv[1]));
2501         }
2502 }
2503 #endif
2504
2505 static CfEntryInfo *
2506 config_find_base( CfEntryInfo *root, struct berval *dn, CfEntryInfo **last )
2507 {
2508         struct berval cdn;
2509         char *c;
2510
2511         if ( !root ) {
2512                 *last = NULL;
2513                 return NULL;
2514         }
2515
2516         if ( dn_match( &root->ce_entry->e_nname, dn ))
2517                 return root;
2518
2519         c = dn->bv_val+dn->bv_len;
2520         for (;*c != ',';c--);
2521
2522         while(root) {
2523                 *last = root;
2524                 for (--c;c>dn->bv_val && *c != ',';c--);
2525                 cdn.bv_val = c;
2526                 if ( *c == ',' )
2527                         cdn.bv_val++;
2528                 cdn.bv_len = dn->bv_len - (cdn.bv_val - dn->bv_val);
2529
2530                 root = root->ce_kids;
2531
2532                 for (;root;root=root->ce_sibs) {
2533                         if ( dn_match( &root->ce_entry->e_nname, &cdn )) {
2534                                 if ( cdn.bv_val == dn->bv_val ) {
2535                                         return root;
2536                                 }
2537                                 break;
2538                         }
2539                 }
2540         }
2541         return root;
2542 }
2543
2544 typedef struct setup_cookie {
2545         CfBackInfo *cfb;
2546         ConfigArgs *ca;
2547 } setup_cookie;
2548
2549 static int
2550 config_ldif_resp( Operation *op, SlapReply *rs )
2551 {
2552         if ( rs->sr_type == REP_SEARCH ) {
2553                 setup_cookie *sc = op->o_callback->sc_private;
2554
2555                 sc->cfb->cb_got_ldif = 1;
2556                 rs->sr_err = config_add_internal( sc->cfb, rs->sr_entry, sc->ca, NULL, NULL );
2557                 if ( rs->sr_err != LDAP_SUCCESS ) {
2558                         Debug( LDAP_DEBUG_ANY, "config error processing %s: %s\n",
2559                                 rs->sr_entry->e_name.bv_val, sc->ca->msg, 0 );
2560                 }
2561         }
2562         return rs->sr_err;
2563 }
2564
2565 /* Configure and read the underlying back-ldif store */
2566 static int
2567 config_setup_ldif( BackendDB *be, const char *dir, int readit ) {
2568         CfBackInfo *cfb = be->be_private;
2569         ConfigArgs c = {0};
2570         ConfigTable *ct;
2571         char *argv[3];
2572         int rc = 0;
2573         setup_cookie sc;
2574         slap_callback cb = { NULL, config_ldif_resp, NULL, NULL };
2575         Connection conn = {0};
2576         char opbuf[OPERATION_BUFFER_SIZE];
2577         Operation *op;
2578         SlapReply rs = {REP_RESULT};
2579         Filter filter = { LDAP_FILTER_PRESENT };
2580         struct berval filterstr = BER_BVC("(objectclass=*)");
2581         struct stat st;
2582
2583         /* Is the config directory available? */
2584         if ( stat( dir, &st ) < 0 ) {
2585                 /* No, so don't bother using the backing store.
2586                  * All changes will be in-memory only.
2587                  */
2588                 return 0;
2589         }
2590                 
2591         cfb->cb_db.bd_info = backend_info( "ldif" );
2592         if ( !cfb->cb_db.bd_info )
2593                 return 0;       /* FIXME: eventually this will be a fatal error */
2594
2595         if ( cfb->cb_db.bd_info->bi_db_init( &cfb->cb_db )) return 1;
2596
2597         /* Mark that back-ldif type is in use */
2598         cfb->cb_db.bd_info->bi_nDB++;
2599
2600         cfb->cb_db.be_suffix = be->be_suffix;
2601         cfb->cb_db.be_nsuffix = be->be_nsuffix;
2602         cfb->cb_db.be_rootdn = be->be_rootdn;
2603         cfb->cb_db.be_rootndn = be->be_rootndn;
2604
2605         ber_str2bv( dir, 0, 1, &cfdir );
2606
2607         c.be = &cfb->cb_db;
2608         c.fname = "slapd";
2609         c.argc = 2;
2610         argv[0] = "directory";
2611         argv[1] = (char *)dir;
2612         argv[2] = NULL;
2613         c.argv = argv;
2614
2615         ct = config_find_keyword( c.be->be_cf_ocs->co_table, &c );
2616         if ( !ct )
2617                 return 1;
2618
2619         if ( config_add_vals( ct, &c ))
2620                 return 1;
2621
2622         if ( backend_startup_one( &cfb->cb_db ))
2623                 return 1;
2624
2625         if ( readit ) {
2626                 void *thrctx = ldap_pvt_thread_pool_context();
2627
2628                 op = (Operation *)opbuf;
2629                 connection_fake_init( &conn, op, thrctx );
2630
2631                 filter.f_desc = slap_schema.si_ad_objectClass;
2632
2633                 op->o_tag = LDAP_REQ_SEARCH;
2634
2635                 op->ors_filter = &filter;
2636                 op->ors_filterstr = filterstr;
2637                 op->ors_scope = LDAP_SCOPE_SUBTREE;
2638
2639                 op->o_dn = be->be_rootdn;
2640                 op->o_ndn = be->be_rootndn;
2641
2642                 op->o_req_dn = be->be_suffix[0];
2643                 op->o_req_ndn = be->be_nsuffix[0];
2644
2645                 op->ors_tlimit = SLAP_NO_LIMIT;
2646                 op->ors_slimit = SLAP_NO_LIMIT;
2647
2648                 op->ors_attrs = slap_anlist_all_attributes;
2649                 op->ors_attrsonly = 0;
2650
2651                 op->o_callback = &cb;
2652                 sc.cfb = cfb;
2653                 sc.ca = &c;
2654                 cb.sc_private = &sc;
2655
2656                 op->o_bd = &cfb->cb_db;
2657                 rc = op->o_bd->be_search( op, &rs );
2658
2659                 ldap_pvt_thread_pool_context_reset( thrctx );
2660         }
2661
2662         cfb->cb_use_ldif = 1;
2663
2664         return rc;
2665 }
2666
2667 static int
2668 CfOc_cmp( const void *c1, const void *c2 ) {
2669         const ConfigOCs *co1 = c1;
2670         const ConfigOCs *co2 = c2;
2671
2672         return ber_bvcmp( co1->co_name, co2->co_name );
2673 }
2674
2675 int
2676 config_register_schema(ConfigTable *ct, ConfigOCs *ocs) {
2677         int i;
2678
2679         i = init_config_attrs( ct );
2680         if ( i ) return i;
2681
2682         /* set up the objectclasses */
2683         i = init_config_ocs( ocs );
2684         if ( i ) return i;
2685
2686         for (i=0; ocs[i].co_def; i++) {
2687                 if ( ocs[i].co_oc ) {
2688                         ocs[i].co_name = &ocs[i].co_oc->soc_cname;
2689                         if ( !ocs[i].co_table )
2690                                 ocs[i].co_table = ct;
2691                         avl_insert( &CfOcTree, &ocs[i], CfOc_cmp, avl_dup_error );
2692                 }
2693         }
2694         return 0;
2695 }
2696
2697 int
2698 read_config(const char *fname, const char *dir) {
2699         BackendDB *be;
2700         CfBackInfo *cfb;
2701         const char *cfdir, *cfname;
2702         int rc;
2703
2704         /* Setup the config backend */
2705         be = backend_db_init( "config" );
2706         if ( !be )
2707                 return 1;
2708
2709         cfb = be->be_private;
2710
2711         /* If no .conf, or a dir was specified, setup the dir */
2712         if ( !fname || dir ) {
2713                 if ( dir ) {
2714                         /* If explicitly given, check for existence */
2715                         struct stat st;
2716
2717                         if ( stat( dir, &st ) < 0 ) {
2718                                 Debug( LDAP_DEBUG_ANY,
2719                                         "invalid config directory %s, error %d\n",
2720                                                 dir, errno, 0 );
2721                                 return 1;
2722                         }
2723                         cfdir = dir;
2724                 } else {
2725                         cfdir = SLAPD_DEFAULT_CONFIGDIR;
2726                 }
2727                 /* if fname is defaulted, try reading .d */
2728                 rc = config_setup_ldif( be, cfdir, !fname );
2729
2730                 /* It's OK if the base object doesn't exist yet */
2731                 if ( rc && rc != LDAP_NO_SUCH_OBJECT )
2732                         return 1;
2733
2734                 /* If we read the config from back-ldif, nothing to do here */
2735                 if ( cfb->cb_got_ldif ) {
2736                         rc = 0;
2737                         goto done;
2738                 }
2739         }
2740
2741         if ( fname )
2742                 cfname = fname;
2743         else
2744                 cfname = SLAPD_DEFAULT_CONFIGFILE;
2745
2746         rc = read_config_file(cfname, 0, NULL, config_back_cf_table);
2747
2748         if ( rc == 0 )
2749                 ber_str2bv( cfname, 0, 1, &cfb->cb_config->c_file );
2750
2751         /* If we got this far and failed, it may be a serious problem. In server
2752          * mode, we should never come to this. However, it may be alright if we're
2753          * using slapadd to create the conf dir.
2754          */
2755         while ( rc ) {
2756                 if ( slapMode & (SLAP_SERVER_MODE|SLAP_TOOL_READMAIN|SLAP_TOOL_READONLY))
2757                         break;
2758                 /* If a config file was explicitly given, fail */
2759                 if ( fname )
2760                         break;
2761                 
2762                 /* Seems to be slapadd with a config dir, let it continue */
2763                 if ( cfb->cb_use_ldif ) {
2764                         rc = 0;
2765                         cfb->cb_got_ldif = 1;
2766                 }
2767                 break;
2768         }
2769
2770 done:
2771         if ( rc == 0 && BER_BVISNULL( &frontendDB->be_schemadn ) ) {
2772                 ber_str2bv( SLAPD_SCHEMA_DN, STRLENOF( SLAPD_SCHEMA_DN ), 1,
2773                         &frontendDB->be_schemadn );
2774                 rc = dnNormalize( 0, NULL, NULL, &frontendDB->be_schemadn, &frontendDB->be_schemandn, NULL );
2775                 if ( rc != LDAP_SUCCESS ) {
2776                         Debug(LDAP_DEBUG_ANY, "read_config: "
2777                                 "unable to normalize default schema DN \"%s\"\n",
2778                                 frontendDB->be_schemadn.bv_val, 0, 0 );
2779                         /* must not happen */
2780                         assert( 0 );
2781                 }
2782         }
2783         return rc;
2784 }
2785
2786 static int
2787 config_back_bind( Operation *op, SlapReply *rs )
2788 {
2789         if ( op->orb_method == LDAP_AUTH_SIMPLE && be_isroot_pw( op )) {
2790                 ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ));
2791                 /* frontend sends result */
2792                 return LDAP_SUCCESS;
2793         }
2794
2795         rs->sr_err = LDAP_INVALID_CREDENTIALS;
2796         send_ldap_result( op, rs );
2797
2798         return rs->sr_err;
2799 }
2800
2801 static int
2802 config_send( Operation *op, SlapReply *rs, CfEntryInfo *ce, int depth )
2803 {
2804         int rc = 0;
2805
2806         if ( test_filter( op, ce->ce_entry, op->ors_filter ) == LDAP_COMPARE_TRUE )
2807         {
2808                 rs->sr_attrs = op->ors_attrs;
2809                 rs->sr_entry = ce->ce_entry;
2810                 rc = send_search_entry( op, rs );
2811         }
2812         if ( op->ors_scope == LDAP_SCOPE_SUBTREE ) {
2813                 if ( ce->ce_kids ) {
2814                         rc = config_send( op, rs, ce->ce_kids, 1 );
2815                         if ( rc ) return rc;
2816                 }
2817                 if ( depth ) {
2818                         for (ce=ce->ce_sibs; ce; ce=ce->ce_sibs) {
2819                                 rc = config_send( op, rs, ce, 0 );
2820                                 if ( rc ) break;
2821                         }
2822                 }
2823         }
2824         return rc;
2825 }
2826
2827 static ConfigTable *
2828 config_find_table( ConfigOCs **colst, int nocs, AttributeDescription *ad )
2829 {
2830         int i, j;
2831
2832         for (j=0; j<nocs; j++) {
2833                 for (i=0; colst[j]->co_table[i].name; i++)
2834                         if ( colst[j]->co_table[i].ad == ad )
2835                                 return &colst[j]->co_table[i];
2836         }
2837         return NULL;
2838 }
2839
2840 /* Sort the attributes of the entry according to the order defined
2841  * in the objectclass, with required attributes occurring before
2842  * allowed attributes. For any attributes with sequencing dependencies
2843  * (e.g., rootDN must be defined after suffix) the objectclass must
2844  * list the attributes in the desired sequence.
2845  */
2846 static void
2847 sort_attrs( Entry *e, ConfigOCs **colst, int nocs )
2848 {
2849         Attribute *a, *head = NULL, *tail = NULL, **prev;
2850         int i, j;
2851
2852         for (i=0; i<nocs; i++) {
2853                 if ( colst[i]->co_oc->soc_required ) {
2854                         AttributeType **at = colst[i]->co_oc->soc_required;
2855                         for (j=0; at[j]; j++) {
2856                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
2857                                         prev = &(*prev)->a_next, a=a->a_next) {
2858                                         if ( a->a_desc == at[j]->sat_ad ) {
2859                                                 *prev = a->a_next;
2860                                                 if (!head) {
2861                                                         head = a;
2862                                                         tail = a;
2863                                                 } else {
2864                                                         tail->a_next = a;
2865                                                         tail = a;
2866                                                 }
2867                                                 break;
2868                                         }
2869                                 }
2870                         }
2871                 }
2872                 if ( colst[i]->co_oc->soc_allowed ) {
2873                         AttributeType **at = colst[i]->co_oc->soc_allowed;
2874                         for (j=0; at[j]; j++) {
2875                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
2876                                         prev = &(*prev)->a_next, a=a->a_next) {
2877                                         if ( a->a_desc == at[j]->sat_ad ) {
2878                                                 *prev = a->a_next;
2879                                                 if (!head) {
2880                                                         head = a;
2881                                                         tail = a;
2882                                                 } else {
2883                                                         tail->a_next = a;
2884                                                         tail = a;
2885                                                 }
2886                                                 break;
2887                                         }
2888                                 }
2889                         }
2890                 }
2891         }
2892         if ( tail ) {
2893                 tail->a_next = e->e_attrs;
2894                 e->e_attrs = head;
2895         }
2896 }
2897
2898 static int
2899 check_vals( ConfigTable *ct, ConfigArgs *ca, void *ptr, int isAttr )
2900 {
2901         Attribute *a = NULL;
2902         AttributeDescription *ad;
2903         BerVarray vals;
2904
2905         int i, rc = 0, sort = 0;
2906
2907         if ( isAttr ) {
2908                 a = ptr;
2909                 ad = a->a_desc;
2910                 vals = a->a_vals;
2911         } else {
2912                 Modifications *ml = ptr;
2913                 ad = ml->sml_desc;
2914                 vals = ml->sml_values;
2915         }
2916
2917         if ( a && ( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL )) {
2918                 sort = 1;
2919                 rc = ordered_value_sort( a, 1 );
2920                 if ( rc ) {
2921                         sprintf(ca->msg, "ordered_value_sort failed on attr %s\n",
2922                                 ad->ad_cname.bv_val );
2923                         return rc;
2924                 }
2925         }
2926         for ( i=0; vals[i].bv_val; i++ ) {
2927                 ca->line = vals[i].bv_val;
2928                 if ( sort ) {
2929                         char *idx = strchr( ca->line, '}' );
2930                         if ( idx ) ca->line = idx+1;
2931                 }
2932                 rc = config_parse_vals( ct, ca, i );
2933                 if ( rc ) {
2934                         break;
2935                 }
2936         }
2937         return rc;
2938 }
2939
2940 static int
2941 check_name_index( CfEntryInfo *parent, ConfigType ce_type, Entry *e,
2942         SlapReply *rs, int *renum )
2943 {
2944         CfEntryInfo *ce;
2945         int index = -1, gotindex = 0, nsibs;
2946         int renumber = 0, tailindex = 0;
2947         char *ptr1, *ptr2;
2948         struct berval rdn;
2949
2950         if ( renum ) *renum = 0;
2951
2952         /* These entries don't get indexed/renumbered */
2953         if ( ce_type == Cft_Global ) return 0;
2954         if ( ce_type == Cft_Schema && parent->ce_type == Cft_Global ) return 0;
2955
2956         if ( ce_type == Cft_Include || ce_type == Cft_Module )
2957                 tailindex = 1;
2958
2959         /* See if the rdn has an index already */
2960         dnRdn( &e->e_name, &rdn );
2961         ptr1 = strchr( e->e_name.bv_val, '{' );
2962         if ( ptr1 && ptr1 - e->e_name.bv_val < rdn.bv_len ) {
2963                 ptr2 = strchr( ptr1, '}' );
2964                 if (!ptr2 || ptr2 - e->e_name.bv_val > rdn.bv_len)
2965                         return LDAP_NAMING_VIOLATION;
2966                 if ( ptr2-ptr1 == 1)
2967                         return LDAP_NAMING_VIOLATION;
2968                 gotindex = 1;
2969                 index = atoi(ptr1+1);
2970                 if ( index < 0 ) {
2971                         /* Special case, we allow -1 for the frontendDB */
2972                         if ( index != -1 || ce_type != Cft_Database ||
2973                                 strncmp( ptr2+1, "frontend,", STRLENOF("frontend,") ))
2974
2975                                 return LDAP_NAMING_VIOLATION;
2976                 }
2977         }
2978
2979         /* count related kids */
2980         for (nsibs=0, ce=parent->ce_kids; ce; ce=ce->ce_sibs) {
2981                 if ( ce->ce_type == ce_type ) nsibs++;
2982         }
2983
2984         if ( index != nsibs ) {
2985                 if ( gotindex ) {
2986                         if ( index < nsibs ) {
2987                                 if ( tailindex ) return LDAP_NAMING_VIOLATION;
2988                                 /* Siblings need to be renumbered */
2989                                 renumber = 1;
2990                         }
2991                 }
2992                 if ( !renumber ) {
2993                         struct berval ival, newrdn, nnewrdn;
2994                         struct berval rtype, rval;
2995                         Attribute *a;
2996                         AttributeDescription *ad = NULL;
2997                         char ibuf[32];
2998                         const char *text;
2999
3000                         rval.bv_val = strchr(rdn.bv_val, '=' ) + 1;
3001                         rval.bv_len = rdn.bv_len - (rval.bv_val - rdn.bv_val);
3002                         rtype.bv_val = rdn.bv_val;
3003                         rtype.bv_len = rval.bv_val - rtype.bv_val - 1;
3004
3005                         /* Find attr */
3006                         slap_bv2ad( &rtype, &ad, &text );
3007                         a = attr_find( e->e_attrs, ad );
3008                         if (!a ) return LDAP_NAMING_VIOLATION;
3009
3010                         ival.bv_val = ibuf;
3011                         ival.bv_len = sprintf( ibuf, IFMT, nsibs );
3012                         
3013                         newrdn.bv_len = rdn.bv_len + ival.bv_len;
3014                         newrdn.bv_val = ch_malloc( newrdn.bv_len+1 );
3015
3016                         if ( tailindex ) {
3017                                 ptr1 = lutil_strncopy( newrdn.bv_val, rdn.bv_val, rdn.bv_len );
3018                                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3019                         } else {
3020                                 int xlen;
3021                                 if ( !gotindex ) {
3022                                         ptr2 = rval.bv_val;
3023                                         xlen = rval.bv_len;
3024                                 } else {
3025                                         xlen = rdn.bv_len - (ptr2 - rdn.bv_val);
3026                                 }
3027                                 ptr1 = lutil_strncopy( newrdn.bv_val, rtype.bv_val,
3028                                         rtype.bv_len );
3029                                 *ptr1++ = '=';
3030                                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3031                                 ptr1 = lutil_strncopy( ptr1, ptr2, xlen );
3032                                 *ptr1 = '\0';
3033                         }
3034
3035                         /* Do the equivalent of ModRDN */
3036                         /* Replace DN / NDN */
3037                         newrdn.bv_len = ptr1 - newrdn.bv_val;
3038                         rdnNormalize( 0, NULL, NULL, &newrdn, &nnewrdn, NULL );
3039                         free( e->e_name.bv_val );
3040                         build_new_dn( &e->e_name, &parent->ce_entry->e_name,
3041                                 &newrdn, NULL );
3042                         free( e->e_nname.bv_val );
3043                         build_new_dn( &e->e_nname, &parent->ce_entry->e_nname,
3044                                 &nnewrdn, NULL );
3045
3046                         /* Replace attr */
3047                         free( a->a_vals[0].bv_val );
3048                         ptr1 = strchr( newrdn.bv_val, '=' ) + 1;
3049                         a->a_vals[0].bv_len = newrdn.bv_len - (ptr1 - newrdn.bv_val);
3050                         a->a_vals[0].bv_val = ch_malloc( a->a_vals[0].bv_len + 1 );
3051                         strcpy( a->a_vals[0].bv_val, ptr1 );
3052
3053                         if ( a->a_nvals != a->a_vals ) {
3054                                 free( a->a_nvals[0].bv_val );
3055                                 ptr1 = strchr( nnewrdn.bv_val, '=' ) + 1;
3056                                 a->a_nvals[0].bv_len = nnewrdn.bv_len - (ptr1 - nnewrdn.bv_val);
3057                                 a->a_nvals[0].bv_val = ch_malloc( a->a_nvals[0].bv_len + 1 );
3058                                 strcpy( a->a_nvals[0].bv_val, ptr1 );
3059                         }
3060                         free( nnewrdn.bv_val );
3061                         free( newrdn.bv_val );
3062                 }
3063         }
3064         if ( renum ) *renum = renumber;
3065         return 0;
3066 }
3067
3068 static ConfigOCs **
3069 count_ocs( Attribute *oc_at, int *nocs )
3070 {
3071         int i, j, n;
3072         ConfigOCs co, *coptr, **colst;
3073
3074         /* count the objectclasses */
3075         for ( i=0; oc_at->a_nvals[i].bv_val; i++ );
3076         n = i;
3077         colst = (ConfigOCs **)ch_malloc( n * sizeof(ConfigOCs *));
3078
3079         for ( i=0, j=0; i<n; i++) {
3080                 co.co_name = &oc_at->a_nvals[i];
3081                 coptr = avl_find( CfOcTree, &co, CfOc_cmp );
3082                 
3083                 /* ignore non-config objectclasses. probably should be
3084                  * an error, general data doesn't belong here.
3085                  */
3086                 if ( !coptr ) continue;
3087
3088                 /* Ignore the root objectclass, it has no implementation.
3089                  */
3090                 if ( coptr->co_type == Cft_Abstract ) continue;
3091                 colst[j++] = coptr;
3092         }
3093         *nocs = j;
3094         return colst;
3095 }
3096
3097 static int
3098 cfAddInclude( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3099 {
3100         if ( p->ce_type != Cft_Global && p->ce_type != Cft_Include )
3101                 return LDAP_CONSTRAINT_VIOLATION;
3102
3103         /* If we're reading from a configdir, don't parse this entry */
3104         if ( ca->lineno )
3105                 return LDAP_COMPARE_TRUE;
3106
3107         cfn = p->ce_private;
3108         ca->private = cfn;
3109         return LDAP_SUCCESS;
3110 }
3111
3112 static int
3113 cfAddSchema( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3114 {
3115         ConfigFile *cfo;
3116
3117         /* This entry is hardcoded, don't re-parse it */
3118         if ( p->ce_type == Cft_Global ) {
3119                 cfn = p->ce_private;
3120                 ca->private = cfn;
3121                 return LDAP_COMPARE_TRUE;
3122         }
3123         if ( p->ce_type != Cft_Schema )
3124                 return LDAP_CONSTRAINT_VIOLATION;
3125
3126         cfn = ch_calloc( 1, sizeof(ConfigFile) );
3127         ca->private = cfn;
3128         cfo = p->ce_private;
3129         cfn->c_sibs = cfo->c_kids;
3130         cfo->c_kids = cfn;
3131         return LDAP_SUCCESS;
3132 }
3133
3134 static int
3135 cfAddDatabase( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3136 {
3137         if ( p->ce_type != Cft_Global )
3138                 return LDAP_CONSTRAINT_VIOLATION;
3139         ca->be = frontendDB;    /* just to get past check_vals */
3140         return LDAP_SUCCESS;
3141 }
3142
3143 static int
3144 cfAddBackend( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3145 {
3146         if ( p->ce_type != Cft_Global )
3147                 return LDAP_CONSTRAINT_VIOLATION;
3148         return LDAP_SUCCESS;
3149 }
3150
3151 static int
3152 cfAddModule( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3153 {
3154         if ( p->ce_type != Cft_Global )
3155                 return LDAP_CONSTRAINT_VIOLATION;
3156         return LDAP_SUCCESS;
3157 }
3158
3159 static int
3160 cfAddOverlay( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3161 {
3162         if ( p->ce_type != Cft_Database )
3163                 return LDAP_CONSTRAINT_VIOLATION;
3164         ca->be = p->ce_be;
3165         return LDAP_SUCCESS;
3166 }
3167
3168 /* Parse an LDAP entry into config directives */
3169 static int
3170 config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca, SlapReply *rs, int *renum )
3171 {
3172         CfEntryInfo *ce, *last;
3173         ConfigOCs **colst;
3174         Attribute *a, *oc_at;
3175         int i, nocs, rc = 0;
3176         struct berval pdn;
3177         ConfigTable *ct;
3178         char *ptr;
3179
3180         /* Make sure parent exists and entry does not */
3181         ce = config_find_base( cfb->cb_root, &e->e_nname, &last );
3182         if ( ce )
3183                 return LDAP_ALREADY_EXISTS;
3184
3185         dnParent( &e->e_nname, &pdn );
3186
3187         /* If last is NULL, the new entry is the root/suffix entry, 
3188          * otherwise last should be the parent.
3189          */
3190         if ( last && !dn_match( &last->ce_entry->e_nname, &pdn )) {
3191                 if ( rs )
3192                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3193                 return LDAP_NO_SUCH_OBJECT;
3194         }
3195
3196         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
3197         if ( !oc_at ) return LDAP_OBJECT_CLASS_VIOLATION;
3198
3199         memset( ca, 0, sizeof(ConfigArgs));
3200
3201         /* Fake the coordinates based on whether we're part of an
3202          * LDAP Add or if reading the config dir
3203          */
3204         if ( rs ) {
3205                 ca->fname = "slapd";
3206                 ca->lineno = 0;
3207         } else {
3208                 ca->fname = cfdir.bv_val;
3209                 ca->lineno = 1;
3210         }
3211
3212         colst = count_ocs( oc_at, &nocs );
3213
3214         /* Only the root can be Cft_Global, everything else must
3215          * have a parent. Only limited nesting arrangements are allowed.
3216          */
3217         rc = LDAP_CONSTRAINT_VIOLATION;
3218         if ( colst[0]->co_type == Cft_Global && !last ) {
3219                 cfn = cfb->cb_config;
3220                 ca->private = cfn;
3221                 ca->be = frontendDB;    /* just to get past check_vals */
3222                 rc = LDAP_SUCCESS;
3223         }
3224
3225         /* Check whether the Add is allowed by its parent, and do
3226          * any necessary arg setup
3227          */
3228         if ( last ) {
3229                 for ( i=0; i<nocs; i++ ) {
3230                         if ( colst[i]->co_ldadd &&
3231                                 ( rc = colst[i]->co_ldadd( last, e, ca ))
3232                                         != LDAP_CONSTRAINT_VIOLATION ) {
3233                                 break;
3234                         }
3235                 }
3236         }
3237
3238         /* Add the entry but don't parse it, we already have its contents */
3239         if ( rc == LDAP_COMPARE_TRUE ) {
3240                 rc = LDAP_SUCCESS;
3241                 goto ok;
3242         }
3243
3244         if ( rc != LDAP_SUCCESS )
3245                 goto done;
3246
3247         /* Parse all the values and check for simple syntax errors before
3248          * performing any set actions.
3249          *
3250          * If doing an LDAPadd, check for indexed names and any necessary
3251          * renaming/renumbering. Entries that don't need indexed names are
3252          * ignored. Entries that need an indexed name and arrive without one
3253          * are assigned to the end. Entries that arrive with an index may
3254          * cause the following entries to be renumbered/bumped down.
3255          *
3256          * Note that "pseudo-indexed" entries (cn=Include{xx}, cn=Module{xx})
3257          * don't allow Adding an entry with an index that's already in use.
3258          * This is flagged as an error (LDAP_ALREADY_EXISTS) up above.
3259          *
3260          * These entries can have auto-assigned indexes (appended to the end)
3261          * but only the other types support auto-renumbering of siblings.
3262          */
3263         rc = check_name_index( last, colst[0]->co_type, e, rs, renum );
3264         if ( rc )
3265                 goto done;
3266
3267         init_config_argv( ca );
3268
3269         /* Make sure we process attrs in the required order */
3270         sort_attrs( e, colst, nocs );
3271
3272         for ( a=e->e_attrs; a; a=a->a_next ) {
3273                 if ( a == oc_at ) continue;
3274                 ct = config_find_table( colst, nocs, a->a_desc );
3275                 if ( !ct ) continue;    /* user data? */
3276                 rc = check_vals( ct, ca, a, 1 );
3277                 if ( rc ) goto done;
3278         }
3279
3280         /* Basic syntax checks are OK. Do the actual settings. */
3281         for ( a=e->e_attrs; a; a=a->a_next ) {
3282                 if ( a == oc_at ) continue;
3283                 ct = config_find_table( colst, nocs, a->a_desc );
3284                 if ( !ct ) continue;    /* user data? */
3285                 for (i=0; a->a_vals[i].bv_val; i++) {
3286                         ca->line = a->a_vals[i].bv_val;
3287                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED ) {
3288                                 ptr = strchr( ca->line, '}' );
3289                                 if ( ptr ) ca->line = ptr+1;
3290                         }
3291                         ca->valx = i;
3292                         rc = config_parse_add( ct, ca );
3293                         if ( rc ) {
3294                                 rc = LDAP_OTHER;
3295                                 goto done;
3296                         }
3297                 }
3298         }
3299 ok:
3300         /* Newly added databases and overlays need to be started up */
3301         if ( CONFIG_ONLINE_ADD( ca )) {
3302                 if ( colst[0]->co_type == Cft_Database ) {
3303                         rc = backend_startup_one( ca->be );
3304
3305                 } else if ( colst[0]->co_type == Cft_Overlay ) {
3306                         if ( ca->bi->bi_db_open ) {
3307                                 BackendInfo *bi_orig = ca->be->bd_info;
3308                                 ca->be->bd_info = ca->bi;
3309                                 rc = ca->bi->bi_db_open( ca->be );
3310                                 ca->be->bd_info = bi_orig;
3311                         }
3312                 }
3313                 if ( rc ) {
3314                         sprintf( ca->msg, "<%s> failed startup", ca->argv[0] );
3315                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
3316                                 ca->log, ca->msg, ca->argv[1] );
3317                         rc = LDAP_OTHER;
3318                         goto done;
3319                 }
3320         }
3321
3322         ce = ch_calloc( 1, sizeof(CfEntryInfo) );
3323         ce->ce_parent = last;
3324         ce->ce_entry = entry_dup( e );
3325         ce->ce_entry->e_private = ce;
3326         ce->ce_type = colst[0]->co_type;
3327         ce->ce_be = ca->be;
3328         ce->ce_bi = ca->bi;
3329         ce->ce_private = ca->private;
3330         if ( !last ) {
3331                 cfb->cb_root = ce;
3332         } else if ( last->ce_kids ) {
3333                 CfEntryInfo *c2;
3334
3335                 for (c2=last->ce_kids; c2 && c2->ce_sibs; c2 = c2->ce_sibs);
3336
3337                 c2->ce_sibs = ce;
3338         } else {
3339                 last->ce_kids = ce;
3340         }
3341
3342 done:
3343         if ( rc ) {
3344                 if ( (colst[0]->co_type == Cft_Database) && ca->be ) {
3345                         if ( ca->be != frontendDB )
3346                                 backend_destroy_one( ca->be, 1 );
3347                 } else if ( (colst[0]->co_type == Cft_Overlay) && ca->bi ) {
3348                         overlay_destroy_one( ca->be, (slap_overinst *)ca->bi );
3349                 }
3350         }
3351
3352         ch_free( ca->argv );
3353         if ( colst ) ch_free( colst );
3354         return rc;
3355 }
3356
3357 /* Parse an LDAP entry into config directives, then store in underlying
3358  * database.
3359  */
3360 static int
3361 config_back_add( Operation *op, SlapReply *rs )
3362 {
3363         CfBackInfo *cfb;
3364         int renumber;
3365         ConfigArgs ca;
3366
3367         if ( !be_isroot( op ) ) {
3368                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
3369                 goto out;
3370         }
3371
3372         cfb = (CfBackInfo *)op->o_bd->be_private;
3373
3374         ldap_pvt_thread_pool_pause( &connection_pool );
3375
3376         /* Strategy:
3377          * 1) check for existence of entry
3378          * 2) check for sibling renumbering
3379          * 3) perform internal add
3380          * 4) store entry in underlying database
3381          * 5) perform any necessary renumbering
3382          */
3383         rs->sr_err = config_add_internal( cfb, op->ora_e, &ca, rs, &renumber );
3384         if ( rs->sr_err != LDAP_SUCCESS ) {
3385                 rs->sr_text = ca.msg;
3386         } else if ( cfb->cb_use_ldif ) {
3387                 BackendDB *be = op->o_bd;
3388                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL };
3389                 op->o_bd = &cfb->cb_db;
3390                 sc.sc_next = op->o_callback;
3391                 op->o_callback = &sc;
3392                 op->o_bd->be_add( op, rs );
3393                 op->o_bd = be;
3394                 op->o_callback = sc.sc_next;
3395         }
3396         if ( renumber ) {
3397         }
3398
3399         ldap_pvt_thread_pool_resume( &connection_pool );
3400
3401 out:
3402         send_ldap_result( op, rs );
3403         return rs->sr_err;
3404 }
3405
3406 typedef struct delrec {
3407         struct delrec *next;
3408         int nidx;
3409         int idx[1];
3410 } delrec;
3411
3412 static int
3413 config_modify_internal( CfEntryInfo *ce, Operation *op, SlapReply *rs,
3414         ConfigArgs *ca )
3415 {
3416         int rc = LDAP_UNWILLING_TO_PERFORM;
3417         Modifications *ml;
3418         Entry *e = ce->ce_entry;
3419         Attribute *save_attrs = e->e_attrs, *oc_at;
3420         ConfigTable *ct;
3421         ConfigOCs **colst;
3422         int i, nocs;
3423         char *ptr;
3424         delrec *dels = NULL, *deltail = NULL;
3425
3426         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
3427         if ( !oc_at ) return LDAP_OBJECT_CLASS_VIOLATION;
3428
3429         colst = count_ocs( oc_at, &nocs );
3430
3431         e->e_attrs = attrs_dup( e->e_attrs );
3432
3433         init_config_argv( ca );
3434         ca->be = ce->ce_be;
3435         ca->bi = ce->ce_bi;
3436         ca->private = ce->ce_private;
3437         ca->ca_entry = e;
3438         strcpy( ca->log, "back-config" );
3439
3440         for (ml = op->orm_modlist; ml; ml=ml->sml_next) {
3441                 ct = config_find_table( colst, nocs, ml->sml_desc );
3442                 switch (ml->sml_op) {
3443                 case LDAP_MOD_DELETE:
3444                 case LDAP_MOD_REPLACE: {
3445                         BerVarray vals = NULL, nvals;
3446                         int *idx = NULL;
3447                         if ( ct && ( ct->arg_type & ARG_NO_DELETE )) {
3448                                 rc = LDAP_OTHER;
3449                                 snprintf(ca->msg, sizeof(ca->msg), "cannot delete %s",
3450                                         ml->sml_desc->ad_cname.bv_val );
3451                                 goto out;
3452                         }
3453                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
3454                                 vals = ml->sml_values;
3455                                 nvals = ml->sml_nvalues;
3456                                 ml->sml_values = NULL;
3457                                 ml->sml_nvalues = NULL;
3458                         }
3459                         /* If we're deleting by values, remember the indexes of the
3460                          * values we deleted.
3461                          */
3462                         if ( ct && ml->sml_values ) {
3463                                 delrec *d;
3464                                 for (i=0; ml->sml_values[i].bv_val; i++);
3465                                 d = ch_malloc( sizeof(delrec) + (i - 1)* sizeof(int));
3466                                 d->nidx = i;
3467                                 d->next = NULL;
3468                                 if ( dels ) {
3469                                         deltail->next = d;
3470                                 } else {
3471                                         dels = d;
3472                                 }
3473                                 deltail = d;
3474                                 idx = d->idx;
3475                         }
3476                         rc = modify_delete_vindex(e, &ml->sml_mod,
3477                                 get_permissiveModify(op),
3478                                 &rs->sr_text, ca->msg, sizeof(ca->msg), idx );
3479                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
3480                                 ml->sml_values = vals;
3481                                 ml->sml_nvalues = nvals;
3482                         }
3483                         if ( !vals )
3484                                 break;
3485                         }
3486                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
3487
3488                 case LDAP_MOD_ADD:
3489                 case SLAP_MOD_SOFTADD: {
3490                         int mop = ml->sml_op;
3491                         int navals = -1;
3492                         ml->sml_op = LDAP_MOD_ADD;
3493                         if ( ct ) {
3494                                 if ( ct->arg_type & ARG_NO_INSERT ) {
3495                                         Attribute *a = attr_find( e->e_attrs, ml->sml_desc );
3496                                         if ( a ) {
3497                                                 for (i = 0; a->a_vals[i].bv_val; i++ );
3498                                                 navals = i;
3499                                         }
3500                                 }
3501                                 for ( i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++ ) {
3502                                         if ( ml->sml_values[i].bv_val[0] == '{' &&
3503                                                 navals >= 0 ) {
3504                                                 int j = strtol( ml->sml_values[i].bv_val+1, NULL, 0 );
3505                                                 if ( j < navals ) {
3506                                                         rc = LDAP_OTHER;
3507                                                         snprintf(ca->msg, sizeof(ca->msg), "cannot insert %s",
3508                                                                 ml->sml_desc->ad_cname.bv_val );
3509                                                         goto out;
3510                                                 }
3511                                         }
3512                                         rc = check_vals( ct, ca, ml, 0 );
3513                                         if ( rc ) goto out;
3514                                 }
3515                         }
3516                         rc = modify_add_values(e, &ml->sml_mod,
3517                                    get_permissiveModify(op),
3518                                    &rs->sr_text, ca->msg, sizeof(ca->msg) );
3519
3520                         /* If value already exists, show success here
3521                          * and ignore this operation down below.
3522                          */
3523                         if ( mop == SLAP_MOD_SOFTADD ) {
3524                                 if ( rc == LDAP_TYPE_OR_VALUE_EXISTS )
3525                                         rc = LDAP_SUCCESS;
3526                                 else
3527                                         mop = LDAP_MOD_ADD;
3528                         }
3529                         ml->sml_op = mop;
3530                         break;
3531                         }
3532
3533                         break;
3534                 case LDAP_MOD_INCREMENT:        /* FIXME */
3535                         break;
3536                 default:
3537                         break;
3538                 }
3539                 if(rc != LDAP_SUCCESS) break;
3540         }
3541         
3542         if(rc == LDAP_SUCCESS) {
3543                 /* check that the entry still obeys the schema */
3544                 rc = entry_schema_check(op, e, NULL, 0,
3545                         &rs->sr_text, ca->msg, sizeof(ca->msg) );
3546         }
3547         if ( rc == LDAP_SUCCESS ) {
3548                 /* Basic syntax checks are OK. Do the actual settings. */
3549                 for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
3550                         ct = config_find_table( colst, nocs, ml->sml_desc );
3551                         if ( !ct ) continue;
3552
3553                         switch (ml->sml_op) {
3554                         case LDAP_MOD_DELETE:
3555                         case LDAP_MOD_REPLACE: {
3556                                 BerVarray vals = NULL, nvals;
3557                                 Attribute *a;
3558                                 delrec *d;
3559
3560                                 a = attr_find( e->e_attrs, ml->sml_desc );
3561
3562                                 if ( ml->sml_op == LDAP_MOD_REPLACE ) {
3563                                         vals = ml->sml_values;
3564                                         nvals = ml->sml_nvalues;
3565                                         ml->sml_values = NULL;
3566                                         ml->sml_nvalues = NULL;
3567                                 }
3568
3569                                 if ( ml->sml_values )
3570                                         d = dels;
3571
3572                                 /* If we didn't delete the whole attribute */
3573                                 if ( ml->sml_values && a ) {
3574                                         struct berval *mvals;
3575                                         int j;
3576
3577                                         if ( ml->sml_nvalues )
3578                                                 mvals = ml->sml_nvalues;
3579                                         else
3580                                                 mvals = ml->sml_values;
3581
3582                                         /* use the indexes we saved up above */
3583                                         for (i=0; i < d->nidx; i++) {
3584                                                 struct berval bv = *mvals++;
3585                                                 if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED &&
3586                                                         bv.bv_val[0] == '{' ) {
3587                                                         ptr = strchr( bv.bv_val, '}' ) + 1;
3588                                                         bv.bv_len -= ptr - bv.bv_val;
3589                                                         bv.bv_val = ptr;
3590                                                 }
3591                                                 ca->line = bv.bv_val;
3592                                                 ca->valx = d->idx[i];
3593                                                 rc = config_del_vals( ct, ca );
3594                                                 if ( rc != LDAP_SUCCESS ) break;
3595                                                 for (j=i+1; j < d->nidx; j++)
3596                                                         if ( d->idx[j] >d->idx[i] )
3597                                                                 d->idx[j]--;
3598                                         }
3599                                 } else {
3600                                         ca->valx = -1;
3601                                         ca->line = NULL;
3602                                         rc = config_del_vals( ct, ca );
3603                                         if ( rc ) rc = LDAP_OTHER;
3604                                 }
3605                                 if ( ml->sml_values ) {
3606                                         ch_free( dels );
3607                                         dels = d->next;
3608                                 }
3609                                 if ( ml->sml_op == LDAP_MOD_REPLACE ) {
3610                                         ml->sml_values = vals;
3611                                         ml->sml_nvalues = nvals;
3612                                 }
3613                                 if ( !vals || rc != LDAP_SUCCESS )
3614                                         break;
3615                                 }
3616                                 /* FALLTHRU: LDAP_MOD_REPLACE && vals */
3617
3618                         case LDAP_MOD_ADD:
3619                                 for (i=0; ml->sml_values[i].bv_val; i++) {
3620                                         ca->line = ml->sml_values[i].bv_val;
3621                                         ca->valx = -1;
3622                                         if ( ml->sml_desc->ad_type->sat_flags & SLAP_AT_ORDERED &&
3623                                                 ca->line[0] == '{' ) {
3624                                                 ptr = strchr( ca->line, '}' );
3625                                                 if ( ptr ) {
3626                                                         ca->valx = strtol( ca->line+1, NULL, 0 );
3627                                                         ca->line = ptr+1;
3628                                                 }
3629                                         }
3630                                         rc = config_parse_add( ct, ca );
3631                                         if ( rc ) {
3632                                                 rc = LDAP_OTHER;
3633                                                 goto out;
3634                                         }
3635                                 }
3636
3637                                 break;
3638                         }
3639                 }
3640         }
3641
3642 out:
3643         if ( ca->cleanup )
3644                 ca->cleanup( ca );
3645         if ( rc == LDAP_SUCCESS ) {
3646                 attrs_free( save_attrs );
3647         } else {
3648                 attrs_free( e->e_attrs );
3649                 e->e_attrs = save_attrs;
3650         }
3651         ch_free( ca->argv );
3652         if ( colst ) ch_free( colst );
3653
3654         return rc;
3655 }
3656
3657 static int
3658 config_back_modify( Operation *op, SlapReply *rs )
3659 {
3660         CfBackInfo *cfb;
3661         CfEntryInfo *ce, *last;
3662         Modifications *ml;
3663         ConfigArgs ca = {0};
3664         struct berval rdn;
3665         char *ptr;
3666         AttributeDescription *rad = NULL;
3667
3668         if ( !be_isroot( op ) ) {
3669                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
3670                 goto out;
3671         }
3672
3673         cfb = (CfBackInfo *)op->o_bd->be_private;
3674
3675         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
3676         if ( !ce ) {
3677                 if ( last )
3678                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3679                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
3680                 goto out;
3681         }
3682
3683         /* Get type of RDN */
3684         rdn = ce->ce_entry->e_nname;
3685         ptr = strchr( rdn.bv_val, '=' );
3686         rdn.bv_len = ptr - rdn.bv_val;
3687         slap_bv2ad( &rdn, &rad, &rs->sr_text );
3688
3689         /* Some basic validation... */
3690         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
3691                 /* Don't allow Modify of RDN; must use ModRdn for that. */
3692                 if ( ml->sml_desc == rad ) {
3693                         rs->sr_err = LDAP_NOT_ALLOWED_ON_RDN;
3694                         rs->sr_text = "Use modrdn to change the entry name";
3695                         goto out;
3696                 }
3697         }
3698
3699         ldap_pvt_thread_pool_pause( &connection_pool );
3700
3701         /* Strategy:
3702          * 1) perform the Modify on the cached Entry.
3703          * 2) verify that the Entry still satisfies the schema.
3704          * 3) perform the individual config operations.
3705          * 4) store Modified entry in underlying LDIF backend.
3706          */
3707         rs->sr_err = config_modify_internal( ce, op, rs, &ca );
3708         if ( rs->sr_err ) {
3709                 rs->sr_text = ca.msg;
3710         } else if ( cfb->cb_use_ldif ) {
3711                 BackendDB *be = op->o_bd;
3712                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL };
3713                 op->o_bd = &cfb->cb_db;
3714                 sc.sc_next = op->o_callback;
3715                 op->o_callback = &sc;
3716                 op->o_bd->be_modify( op, rs );
3717                 op->o_bd = be;
3718                 op->o_callback = sc.sc_next;
3719         }
3720
3721         ldap_pvt_thread_pool_resume( &connection_pool );
3722 out:
3723         send_ldap_result( op, rs );
3724         return rs->sr_err;
3725 }
3726
3727 static int
3728 config_back_modrdn( Operation *op, SlapReply *rs )
3729 {
3730         CfBackInfo *cfb;
3731         CfEntryInfo *ce, *last;
3732
3733         if ( !be_isroot( op ) ) {
3734                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
3735                 goto out;
3736         }
3737
3738         cfb = (CfBackInfo *)op->o_bd->be_private;
3739
3740         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
3741         if ( !ce ) {
3742                 if ( last )
3743                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3744                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
3745                 goto out;
3746         }
3747
3748         /* We don't allow moving objects to new parents.
3749          * Generally we only allow reordering a set of ordered entries.
3750          */
3751         if ( op->orr_newSup ) {
3752                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3753                 goto out;
3754         }
3755         ldap_pvt_thread_pool_pause( &connection_pool );
3756
3757         ldap_pvt_thread_pool_resume( &connection_pool );
3758 out:
3759         send_ldap_result( op, rs );
3760         return rs->sr_err;
3761 }
3762
3763 static int
3764 config_back_search( Operation *op, SlapReply *rs )
3765 {
3766         CfBackInfo *cfb;
3767         CfEntryInfo *ce, *last;
3768
3769         if ( !be_isroot( op ) ) {
3770                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
3771                 goto out;
3772         }
3773
3774         cfb = (CfBackInfo *)op->o_bd->be_private;
3775
3776         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
3777         if ( !ce ) {
3778                 if ( last )
3779                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3780                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
3781                 goto out;
3782         }
3783         switch ( op->ors_scope ) {
3784         case LDAP_SCOPE_BASE:
3785         case LDAP_SCOPE_SUBTREE:
3786                 config_send( op, rs, ce, 0 );
3787                 break;
3788                 
3789         case LDAP_SCOPE_ONELEVEL:
3790                 for (ce = ce->ce_kids; ce; ce=ce->ce_sibs) {
3791                         config_send( op, rs, ce, 1 );
3792                 }
3793                 break;
3794         }
3795                 
3796         rs->sr_err = LDAP_SUCCESS;
3797 out:
3798         send_ldap_result( op, rs );
3799         return 0;
3800 }
3801
3802 static void
3803 config_build_attrs( Entry *e, AttributeType **at, AttributeDescription *ad,
3804         ConfigTable *ct, ConfigArgs *c )
3805 {
3806         int i, rc;
3807
3808         for (; at && *at; at++) {
3809                 /* Skip the naming attr */
3810                 if ((*at)->sat_ad == ad || (*at)->sat_ad == slap_schema.si_ad_cn )
3811                         continue;
3812                 for (i=0;ct[i].name;i++) {
3813                         if (ct[i].ad == (*at)->sat_ad) {
3814                                 rc = config_get_vals(&ct[i], c);
3815                                 if (rc == LDAP_SUCCESS) {
3816                                         if ( c->rvalue_nvals )
3817                                                 attr_merge(e, ct[i].ad, c->rvalue_vals,
3818                                                         c->rvalue_nvals);
3819                                         else
3820                                                 attr_merge_normalize(e, ct[i].ad,
3821                                                         c->rvalue_vals, NULL);
3822                                         ber_bvarray_free( c->rvalue_nvals );
3823                                         ber_bvarray_free( c->rvalue_vals );
3824                                 }
3825                                 break;
3826                         }
3827                 }
3828         }
3829 }
3830
3831 Entry *
3832 config_build_entry( Operation *op, SlapReply *rs, CfEntryInfo *parent,
3833         ConfigArgs *c, struct berval *rdn, ConfigOCs *main, ConfigOCs *extra )
3834 {
3835         Entry *e = ch_calloc( 1, sizeof(Entry) );
3836         CfEntryInfo *ce = ch_calloc( 1, sizeof(CfEntryInfo) );
3837         struct berval val;
3838         struct berval ad_name;
3839         AttributeDescription *ad = NULL;
3840         int rc;
3841         char *ptr;
3842         const char *text;
3843         Attribute *oc_at;
3844         struct berval pdn;
3845         ObjectClass *oc;
3846         CfEntryInfo *ceprev = NULL;
3847
3848         e->e_private = ce;
3849         ce->ce_entry = e;
3850         ce->ce_parent = parent;
3851         if ( parent ) {
3852                 pdn = parent->ce_entry->e_nname;
3853                 if ( parent->ce_kids )
3854                         for ( ceprev = parent->ce_kids; ceprev->ce_sibs;
3855                                 ceprev = ceprev->ce_sibs );
3856         } else {
3857                 BER_BVZERO( &pdn );
3858         }
3859
3860         ce->ce_type = main->co_type;
3861         ce->ce_private = c->private;
3862         ce->ce_be = c->be;
3863         ce->ce_bi = c->bi;
3864
3865         build_new_dn( &e->e_name, &pdn, rdn, NULL );
3866         ber_dupbv( &e->e_nname, &e->e_name );
3867
3868         attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
3869                 main->co_name, NULL );
3870         if ( extra )
3871                 attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
3872                         extra->co_name, NULL );
3873         ptr = strchr(rdn->bv_val, '=');
3874         ad_name.bv_val = rdn->bv_val;
3875         ad_name.bv_len = ptr - rdn->bv_val;
3876         rc = slap_bv2ad( &ad_name, &ad, &text );
3877         if ( rc ) {
3878                 return NULL;
3879         }
3880         val.bv_val = ptr+1;
3881         val.bv_len = rdn->bv_len - (val.bv_val - rdn->bv_val);
3882         attr_merge_normalize_one(e, ad, &val, NULL );
3883
3884         oc = main->co_oc;
3885         if ( oc->soc_required )
3886                 config_build_attrs( e, oc->soc_required, ad, main->co_table, c );
3887
3888         if ( oc->soc_allowed )
3889                 config_build_attrs( e, oc->soc_allowed, ad, main->co_table, c );
3890
3891         if ( extra ) {
3892                 oc = extra->co_oc;
3893                 if ( oc->soc_required )
3894                         config_build_attrs( e, oc->soc_required, ad, extra->co_table, c );
3895
3896                 if ( oc->soc_allowed )
3897                         config_build_attrs( e, oc->soc_allowed, ad, extra->co_table, c );
3898         }
3899
3900         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
3901         rc = structural_class(oc_at->a_vals, &val, NULL, &text, c->msg,
3902                 sizeof(c->msg));
3903         attr_merge_normalize_one(e, slap_schema.si_ad_structuralObjectClass, &val, NULL );
3904         if ( op ) {
3905                 op->ora_e = e;
3906                 op->o_bd->be_add( op, rs );
3907         }
3908         if ( ceprev ) {
3909                 ceprev->ce_sibs = ce;
3910         } else if ( parent ) {
3911                 parent->ce_kids = ce;
3912         }
3913
3914         return e;
3915 }
3916
3917 static void
3918 config_build_schema_inc( ConfigArgs *c, CfEntryInfo *ceparent,
3919         Operation *op, SlapReply *rs )
3920 {
3921         Entry *e;
3922         ConfigFile *cf = c->private;
3923         char *ptr;
3924         struct berval bv;
3925
3926         for (; cf; cf=cf->c_sibs, c->depth++) {
3927                 c->value_dn.bv_val = c->log;
3928                 bv.bv_val = strrchr(cf->c_file.bv_val, LDAP_DIRSEP[0]);
3929                 if ( !bv.bv_val ) {
3930                         bv = cf->c_file;
3931                 } else {
3932                         bv.bv_val++;
3933                         bv.bv_len = cf->c_file.bv_len - (bv.bv_val - cf->c_file.bv_val);
3934                 }
3935                 ptr = strchr( bv.bv_val, '.' );
3936                 if ( ptr )
3937                         bv.bv_len = ptr - bv.bv_val;
3938                 c->value_dn.bv_len = sprintf(c->value_dn.bv_val, "cn=" IFMT, c->depth);
3939                 strncpy( c->value_dn.bv_val + c->value_dn.bv_len, bv.bv_val,
3940                         bv.bv_len );
3941                 c->value_dn.bv_len += bv.bv_len;
3942                 c->value_dn.bv_val[c->value_dn.bv_len] ='\0';
3943
3944                 c->private = cf;
3945                 e = config_build_entry( op, rs, ceparent, c, &c->value_dn,
3946                         &CFOC_SCHEMA, NULL );
3947                 if ( e && cf->c_kids ) {
3948                         c->private = cf->c_kids;
3949                         config_build_schema_inc( c, e->e_private, op, rs );
3950                 }
3951         }
3952 }
3953
3954 static void
3955 config_build_includes( ConfigArgs *c, CfEntryInfo *ceparent,
3956         Operation *op, SlapReply *rs )
3957 {
3958         Entry *e;
3959         int i;
3960         ConfigFile *cf = c->private;
3961
3962         for (i=0; cf; cf=cf->c_sibs, i++) {
3963                 c->value_dn.bv_val = c->log;
3964                 c->value_dn.bv_len = sprintf(c->value_dn.bv_val, "cn=include" IFMT, i);
3965                 c->private = cf;
3966                 e = config_build_entry( op, rs, ceparent, c, &c->value_dn,
3967                         &CFOC_INCLUDE, NULL );
3968                 if ( e && cf->c_kids ) {
3969                         c->private = cf->c_kids;
3970                         config_build_includes( c, e->e_private, op, rs );
3971                 }
3972         }
3973 }
3974
3975 #ifdef SLAPD_MODULES
3976
3977 static void
3978 config_build_modules( ConfigArgs *c, CfEntryInfo *ceparent,
3979         Operation *op, SlapReply *rs )
3980 {
3981         int i;
3982         ModPaths *mp;
3983
3984         for (i=0, mp=&modpaths; mp; mp=mp->mp_next, i++) {
3985                 if ( BER_BVISNULL( &mp->mp_path ) && !mp->mp_loads )
3986                         continue;
3987                 c->value_dn.bv_val = c->log;
3988                 c->value_dn.bv_len = sprintf(c->value_dn.bv_val, "cn=module" IFMT, i);
3989                 c->private = mp;
3990                 config_build_entry( op, rs, ceparent, c, &c->value_dn,
3991                         &CFOC_MODULE, NULL );
3992         }
3993 }
3994 #endif
3995
3996 static int
3997 config_back_db_open( BackendDB *be )
3998 {
3999         CfBackInfo *cfb = be->be_private;
4000         struct berval rdn;
4001         Entry *e, *parent;
4002         CfEntryInfo *ce, *ceparent;
4003         int i;
4004         BackendInfo *bi;
4005         ConfigArgs c;
4006         Connection conn = {0};
4007         char opbuf[OPERATION_BUFFER_SIZE];
4008         Operation *op;
4009         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
4010         SlapReply rs = {REP_RESULT};
4011         void *thrctx = NULL;
4012
4013         /* If we read the config from back-ldif, nothing to do here */
4014         if ( cfb->cb_got_ldif )
4015                 return 0;
4016
4017         if ( cfb->cb_use_ldif ) {
4018                 thrctx = ldap_pvt_thread_pool_context();
4019                 op = (Operation *)opbuf;
4020                 connection_fake_init( &conn, op, thrctx );
4021
4022                 op->o_dn = be->be_rootdn;
4023                 op->o_ndn = be->be_rootndn;
4024
4025                 op->o_tag = LDAP_REQ_ADD;
4026                 op->o_callback = &cb;
4027                 op->o_bd = &cfb->cb_db;
4028         } else {
4029                 op = NULL;
4030         }
4031
4032         /* create root of tree */
4033         rdn = config_rdn;
4034         c.private = cfb->cb_config;
4035         c.be = frontendDB;
4036         e = config_build_entry( op, &rs, NULL, &c, &rdn, &CFOC_GLOBAL, NULL );
4037         ce = e->e_private;
4038         cfb->cb_root = ce;
4039
4040         parent = e;
4041         ceparent = ce;
4042
4043         /* Create includeFile nodes */
4044         if ( cfb->cb_config->c_kids ) {
4045                 c.depth = 0;
4046                 c.private = cfb->cb_config->c_kids;
4047                 config_build_includes( &c, ceparent, op, &rs );
4048         }
4049
4050 #ifdef SLAPD_MODULES
4051         /* Create Module nodes... */
4052         if ( modpaths.mp_loads ) {
4053                 config_build_modules( &c, ceparent, op, &rs );
4054         }
4055 #endif
4056
4057         /* Create schema nodes... cn=schema will contain the hardcoded core
4058          * schema, read-only. Child objects will contain runtime loaded schema
4059          * files.
4060          */
4061         rdn = schema_rdn;
4062         c.private = NULL;
4063         e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_SCHEMA, NULL );
4064         ce = e->e_private;
4065
4066         /* Create schema nodes for included schema... */
4067         if ( cfb->cb_config->c_kids ) {
4068                 c.depth = 0;
4069                 c.private = cfb->cb_config->c_kids;
4070                 config_build_schema_inc( &c, ce, op, &rs );
4071         }
4072
4073         /* Create backend nodes. Skip if they don't provide a cf_table.
4074          * There usually aren't any of these.
4075          */
4076         
4077         c.line = 0;
4078         LDAP_STAILQ_FOREACH( bi, &backendInfo, bi_next) {
4079                 if (!bi->bi_cf_ocs) continue;
4080                 if (!bi->bi_private) continue;
4081
4082                 rdn.bv_val = c.log;
4083                 rdn.bv_len = sprintf(rdn.bv_val, "%s=%s", cfAd_backend->ad_cname.bv_val, bi->bi_type);
4084                 c.bi = bi;
4085                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_BACKEND,
4086                         bi->bi_cf_ocs );
4087         }
4088
4089         /* Create database nodes... */
4090         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
4091         LDAP_STAILQ_NEXT(frontendDB, be_next) = LDAP_STAILQ_FIRST(&backendDB);
4092         for ( i = -1, be = frontendDB ; be;
4093                 i++, be = LDAP_STAILQ_NEXT( be, be_next )) {
4094                 slap_overinfo *oi = NULL;
4095
4096                 if ( overlay_is_over( be )) {
4097                         oi = be->bd_info->bi_private;
4098                         bi = oi->oi_orig;
4099                 } else {
4100                         bi = be->bd_info;
4101                 }
4102                 rdn.bv_val = c.log;
4103                 rdn.bv_len = sprintf(rdn.bv_val, "%s=" IFMT "%s", cfAd_database->ad_cname.bv_val,
4104                         i, bi->bi_type);
4105                 c.be = be;
4106                 c.bi = bi;
4107                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_DATABASE,
4108                         be->be_cf_ocs );
4109                 ce = e->e_private;
4110                 if ( be->be_cf_ocs && be->be_cf_ocs->co_cfadd )
4111                         be->be_cf_ocs->co_cfadd( op, &rs, e, &c );
4112                 /* Iterate through overlays */
4113                 if ( oi ) {
4114                         slap_overinst *on;
4115                         Entry *oe;
4116                         int j;
4117
4118                         for (j=0,on=oi->oi_list; on; j++,on=on->on_next) {
4119                                 rdn.bv_val = c.log;
4120                                 rdn.bv_len = sprintf(rdn.bv_val, "%s=" IFMT "%s",
4121                                         cfAd_overlay->ad_cname.bv_val, j, on->on_bi.bi_type );
4122                                 c.be = be;
4123                                 c.bi = &on->on_bi;
4124                                 oe = config_build_entry( op, &rs, ce, &c, &rdn,
4125                                         &CFOC_OVERLAY, c.bi->bi_cf_ocs );
4126                                 if ( c.bi->bi_cf_ocs && c.bi->bi_cf_ocs->co_cfadd )
4127                                         c.bi->bi_cf_ocs->co_cfadd( op, &rs, oe, &c );
4128                         }
4129                 }
4130         }
4131         if ( thrctx )
4132                 ldap_pvt_thread_pool_context_reset( thrctx );
4133
4134         return 0;
4135 }
4136
4137 static void
4138 cfb_free_cffile( ConfigFile *cf )
4139 {
4140         ConfigFile *next;
4141
4142         for (; cf; cf=next) {
4143                 next = cf->c_sibs;
4144                 if ( cf->c_kids )
4145                         cfb_free_cffile( cf->c_kids );
4146                 ch_free( cf->c_file.bv_val );
4147                 ber_bvarray_free( cf->c_dseFiles );
4148                 ch_free( cf );
4149         }
4150 }
4151
4152 static void
4153 cfb_free_entries( CfEntryInfo *ce )
4154 {
4155         CfEntryInfo *next;
4156
4157         for (; ce; ce=next) {
4158                 next = ce->ce_sibs;
4159                 if ( ce->ce_kids )
4160                         cfb_free_entries( ce->ce_kids );
4161                 ce->ce_entry->e_private = NULL;
4162                 entry_free( ce->ce_entry );
4163                 ch_free( ce );
4164         }
4165 }
4166
4167 static int
4168 config_back_db_close( BackendDB *be )
4169 {
4170         CfBackInfo *cfb = be->be_private;
4171
4172         cfb_free_entries( cfb->cb_root );
4173         cfb->cb_root = NULL;
4174
4175         if ( cfb->cb_db.bd_info ) {
4176                 backend_shutdown( &cfb->cb_db );
4177         }
4178
4179         return 0;
4180 }
4181
4182 static int
4183 config_back_db_destroy( BackendDB *be )
4184 {
4185         CfBackInfo *cfb = be->be_private;
4186
4187         cfb_free_cffile( cfb->cb_config );
4188
4189         ch_free( cfdir.bv_val );
4190
4191         avl_free( CfOcTree, NULL );
4192
4193         if ( cfb->cb_db.bd_info ) {
4194                 cfb->cb_db.be_suffix = NULL;
4195                 cfb->cb_db.be_nsuffix = NULL;
4196                 BER_BVZERO( &cfb->cb_db.be_rootdn );
4197                 BER_BVZERO( &cfb->cb_db.be_rootndn );
4198
4199                 backend_destroy_one( &cfb->cb_db, 0 );
4200         }
4201
4202         free( be->be_private );
4203
4204         loglevel_destroy();
4205
4206         return 0;
4207 }
4208
4209 static int
4210 config_back_db_init( BackendDB *be )
4211 {
4212         struct berval dn;
4213         CfBackInfo *cfb;
4214
4215         cfb = ch_calloc( 1, sizeof(CfBackInfo));
4216         cfb->cb_config = ch_calloc( 1, sizeof(ConfigFile));
4217         cfn = cfb->cb_config;
4218         be->be_private = cfb;
4219
4220         ber_dupbv( &be->be_rootdn, &config_rdn );
4221         ber_dupbv( &be->be_rootndn, &be->be_rootdn );
4222         ber_dupbv( &dn, &be->be_rootdn );
4223         ber_bvarray_add( &be->be_suffix, &dn );
4224         ber_dupbv( &dn, &be->be_rootdn );
4225         ber_bvarray_add( &be->be_nsuffix, &dn );
4226
4227         /* Hide from namingContexts */
4228         SLAP_BFLAGS(be) |= SLAP_BFLAG_CONFIG;
4229
4230         return 0;
4231 }
4232
4233 static int
4234 config_back_destroy( BackendInfo *bi )
4235 {
4236         ldif_must_b64_encode_release();
4237         return 0;
4238 }
4239
4240 static int
4241 config_tool_entry_open( BackendDB *be, int mode )
4242 {
4243         CfBackInfo *cfb = be->be_private;
4244         BackendInfo *bi = cfb->cb_db.bd_info;
4245
4246         if ( bi && bi->bi_tool_entry_open )
4247                 return bi->bi_tool_entry_open( &cfb->cb_db, mode );
4248         else
4249                 return -1;
4250         
4251 }
4252
4253 static int
4254 config_tool_entry_close( BackendDB *be )
4255 {
4256         CfBackInfo *cfb = be->be_private;
4257         BackendInfo *bi = cfb->cb_db.bd_info;
4258
4259         if ( bi && bi->bi_tool_entry_close )
4260                 return bi->bi_tool_entry_close( &cfb->cb_db );
4261         else
4262                 return -1;
4263 }
4264
4265 static ID
4266 config_tool_entry_first( BackendDB *be )
4267 {
4268         CfBackInfo *cfb = be->be_private;
4269         BackendInfo *bi = cfb->cb_db.bd_info;
4270
4271         if ( bi && bi->bi_tool_entry_first )
4272                 return bi->bi_tool_entry_first( &cfb->cb_db );
4273         else
4274                 return NOID;
4275 }
4276
4277 static ID
4278 config_tool_entry_next( BackendDB *be )
4279 {
4280         CfBackInfo *cfb = be->be_private;
4281         BackendInfo *bi = cfb->cb_db.bd_info;
4282
4283         if ( bi && bi->bi_tool_entry_next )
4284                 return bi->bi_tool_entry_next( &cfb->cb_db );
4285         else
4286                 return NOID;
4287 }
4288
4289 static Entry *
4290 config_tool_entry_get( BackendDB *be, ID id )
4291 {
4292         CfBackInfo *cfb = be->be_private;
4293         BackendInfo *bi = cfb->cb_db.bd_info;
4294
4295         if ( bi && bi->bi_tool_entry_get )
4296                 return bi->bi_tool_entry_get( &cfb->cb_db, id );
4297         else
4298                 return NULL;
4299 }
4300
4301 static ID
4302 config_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
4303 {
4304         CfBackInfo *cfb = be->be_private;
4305         BackendInfo *bi = cfb->cb_db.bd_info;
4306         ConfigArgs ca;
4307
4308         if ( bi && bi->bi_tool_entry_put &&
4309                 config_add_internal( cfb, e, &ca, NULL, NULL ) == 0 )
4310                 return bi->bi_tool_entry_put( &cfb->cb_db, e, text );
4311         else
4312                 return NOID;
4313 }
4314
4315 static struct {
4316         char *name;
4317         AttributeDescription **desc;
4318 } ads[] = {
4319         { "backend", &cfAd_backend },
4320         { "database", &cfAd_database },
4321         { "include", &cfAd_include },
4322         { "overlay", &cfAd_overlay },
4323         { NULL, NULL }
4324 };
4325
4326 /* Notes:
4327  *   add / delete: all types that may be added or deleted must use an
4328  * X-ORDERED attributeType for their RDN. Adding and deleting entries
4329  * should automatically renumber the index of any siblings as needed,
4330  * so that no gaps in the numbering sequence exist after the add/delete
4331  * is completed.
4332  *   What can be added:
4333  *     schema objects
4334  *     backend objects for backend-specific config directives
4335  *     database objects
4336  *     overlay objects
4337  *
4338  *   delete: probably no support this time around.
4339  *
4340  *   modrdn: generally not done. Will be invoked automatically by add/
4341  * delete to update numbering sequence. Perform as an explicit operation
4342  * so that the renumbering effect may be replicated. Subtree rename must
4343  * be supported, since renumbering a database will affect all its child
4344  * overlays.
4345  *
4346  *  modify: must be fully supported. 
4347  */
4348
4349 int
4350 config_back_initialize( BackendInfo *bi )
4351 {
4352         ConfigTable             *ct = config_back_cf_table;
4353         char                    *argv[4];
4354         int                     i;
4355         AttributeDescription    *ad = NULL;
4356         const char              *text;
4357         static char             *controls[] = {
4358                 LDAP_CONTROL_MANAGEDSAIT,
4359                 NULL
4360         };
4361
4362         bi->bi_controls = controls;
4363
4364         bi->bi_open = 0;
4365         bi->bi_close = 0;
4366         bi->bi_config = 0;
4367         bi->bi_destroy = config_back_destroy;
4368
4369         bi->bi_db_init = config_back_db_init;
4370         bi->bi_db_config = 0;
4371         bi->bi_db_open = config_back_db_open;
4372         bi->bi_db_close = config_back_db_close;
4373         bi->bi_db_destroy = config_back_db_destroy;
4374
4375         bi->bi_op_bind = config_back_bind;
4376         bi->bi_op_unbind = 0;
4377         bi->bi_op_search = config_back_search;
4378         bi->bi_op_compare = 0;
4379         bi->bi_op_modify = config_back_modify;
4380         bi->bi_op_modrdn = config_back_modrdn;
4381         bi->bi_op_add = config_back_add;
4382         bi->bi_op_delete = 0;
4383         bi->bi_op_abandon = 0;
4384
4385         bi->bi_extended = 0;
4386
4387         bi->bi_chk_referrals = 0;
4388
4389 #ifdef SLAP_OVERLAY_ACCESS
4390         bi->bi_access_allowed = slap_access_always_allowed;
4391 #endif /* SLAP_OVERLAY_ACCESS */
4392
4393         bi->bi_connection_init = 0;
4394         bi->bi_connection_destroy = 0;
4395
4396         bi->bi_tool_entry_open = config_tool_entry_open;
4397         bi->bi_tool_entry_close = config_tool_entry_close;
4398         bi->bi_tool_entry_first = config_tool_entry_first;
4399         bi->bi_tool_entry_next = config_tool_entry_next;
4400         bi->bi_tool_entry_get = config_tool_entry_get;
4401         bi->bi_tool_entry_put = config_tool_entry_put;
4402
4403         /* Make sure we don't exceed the bits reserved for userland */
4404         assert( ( ( CFG_LAST - 1 ) & ARGS_USERLAND ) == ( CFG_LAST - 1 ) );
4405
4406         argv[3] = NULL;
4407         for (i=0; OidMacros[i].name; i++ ) {
4408                 argv[1] = OidMacros[i].name;
4409                 argv[2] = OidMacros[i].oid;
4410                 parse_oidm( "slapd", i, 3, argv, 0, NULL );
4411         }
4412
4413         bi->bi_cf_ocs = cf_ocs;
4414
4415         i = config_register_schema( ct, cf_ocs );
4416         if ( i ) return i;
4417
4418         /* setup olcRootPW to be base64-encoded when written in LDIF form;
4419          * basically, we don't care if it fails */
4420         i = slap_str2ad( "olcRootPW", &ad, &text );
4421         if ( i ) {
4422                 Debug( LDAP_DEBUG_ANY, "config_back_initialize: "
4423                         "warning, unable to get \"olcRootPW\" "
4424                         "attribute description: %d: %s\n",
4425                         i, text, 0 );
4426         } else {
4427                 (void)ldif_must_b64_encode_register( ad->ad_cname.bv_val,
4428                         ad->ad_type->sat_oid );
4429         }
4430
4431         /* set up the notable AttributeDescriptions */
4432         i = 0;
4433         for (;ct->name;ct++) {
4434                 if (strcmp(ct->name, ads[i].name)) continue;
4435                 *ads[i].desc = ct->ad;
4436                 i++;
4437                 if (!ads[i].name) break;
4438         }
4439
4440         return 0;
4441 }
4442