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