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