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