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