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