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