]> git.sur5r.net Git - openldap/blob - servers/slapd/bconfig.c
Partially resurrect cn=Include stuff - parse from LDIF and ignore.
[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-2007 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 #define CONFIG_RDN      "cn=config"
41 #define SCHEMA_RDN      "cn=schema"
42
43 static struct berval config_rdn = BER_BVC(CONFIG_RDN);
44 static struct berval schema_rdn = BER_BVC(SCHEMA_RDN);
45
46 extern int slap_DN_strict;      /* dn.c */
47
48 #ifdef SLAPD_MODULES
49 typedef struct modpath_s {
50         struct modpath_s *mp_next;
51         struct berval mp_path;
52         BerVarray mp_loads;
53 } ModPaths;
54
55 static ModPaths modpaths, *modlast = &modpaths, *modcur = &modpaths;
56 #endif
57
58 typedef struct ConfigFile {
59         struct ConfigFile *c_sibs;
60         struct ConfigFile *c_kids;
61         struct berval c_file;
62         AttributeType *c_at_head, *c_at_tail;
63         ContentRule *c_cr_head, *c_cr_tail;
64         ObjectClass *c_oc_head, *c_oc_tail;
65         OidMacro *c_om_head, *c_om_tail;
66         BerVarray c_dseFiles;
67 } ConfigFile;
68
69 typedef struct {
70         ConfigFile *cb_config;
71         CfEntryInfo *cb_root;
72         BackendDB       cb_db;  /* underlying database */
73         int             cb_got_ldif;
74         int             cb_use_ldif;
75 } CfBackInfo;
76
77 static CfBackInfo cfBackInfo;
78
79 static char     *passwd_salt;
80 static char     *logfileName;
81 #ifdef SLAP_AUTH_REWRITE
82 static BerVarray authz_rewrites;
83 #endif
84
85 static struct berval cfdir;
86
87 /* Private state */
88 static AttributeDescription *cfAd_backend, *cfAd_database, *cfAd_overlay,
89         *cfAd_include, *cfAd_attr, *cfAd_oc, *cfAd_om;
90
91 static ConfigFile *cfn;
92
93 static Avlnode *CfOcTree;
94
95 /* System schema state */
96 extern AttributeType *at_sys_tail;      /* at.c */
97 extern ObjectClass *oc_sys_tail;        /* oc.c */
98 extern OidMacro *om_sys_tail;   /* oidm.c */
99 static AttributeType *cf_at_tail;
100 static ObjectClass *cf_oc_tail;
101 static OidMacro *cf_om_tail;
102
103 static int config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca,
104         SlapReply *rs, int *renumber, Operation *op );
105
106 static int config_check_schema( Operation *op, CfBackInfo *cfb );
107
108 static ConfigDriver config_fname;
109 static ConfigDriver config_cfdir;
110 static ConfigDriver config_generic;
111 static ConfigDriver config_search_base;
112 static ConfigDriver config_passwd_hash;
113 static ConfigDriver config_schema_dn;
114 static ConfigDriver config_sizelimit;
115 static ConfigDriver config_timelimit;
116 static ConfigDriver config_overlay;
117 static ConfigDriver config_subordinate; 
118 static ConfigDriver config_suffix; 
119 static ConfigDriver config_rootdn;
120 static ConfigDriver config_rootpw;
121 static ConfigDriver config_restrict;
122 static ConfigDriver config_allows;
123 static ConfigDriver config_disallows;
124 static ConfigDriver config_requires;
125 static ConfigDriver config_security;
126 static ConfigDriver config_referral;
127 static ConfigDriver config_loglevel;
128 static ConfigDriver config_updatedn;
129 static ConfigDriver config_updateref;
130 static ConfigDriver config_include;
131 static ConfigDriver config_obsolete;
132 #ifdef HAVE_TLS
133 static ConfigDriver config_tls_option;
134 static ConfigDriver config_tls_config;
135 #endif
136 extern ConfigDriver syncrepl_config;
137
138 enum {
139         CFG_ACL = 1,
140         CFG_BACKEND,
141         CFG_DATABASE,
142         CFG_TLS_RAND,
143         CFG_TLS_CIPHER,
144         CFG_TLS_CERT_FILE,
145         CFG_TLS_CERT_KEY,
146         CFG_TLS_CA_PATH,
147         CFG_TLS_CA_FILE,
148         CFG_TLS_DH_FILE,
149         CFG_TLS_VERIFY,
150         CFG_TLS_CRLCHECK,
151         CFG_TLS_CRL_FILE,
152         CFG_CONCUR,
153         CFG_THREADS,
154         CFG_SALT,
155         CFG_LIMITS,
156         CFG_RO,
157         CFG_REWRITE,
158         CFG_DEPTH,
159         CFG_OID,
160         CFG_OC,
161         CFG_DIT,
162         CFG_ATTR,
163         CFG_ATOPT,
164         CFG_ROOTDSE,
165         CFG_LOGFILE,
166         CFG_PLUGIN,
167         CFG_MODLOAD,
168         CFG_MODPATH,
169         CFG_LASTMOD,
170         CFG_AZPOLICY,
171         CFG_AZREGEXP,
172         CFG_SASLSECP,
173         CFG_SSTR_IF_MAX,
174         CFG_SSTR_IF_MIN,
175         CFG_TTHREADS,
176         CFG_MIRRORMODE,
177         CFG_HIDDEN,
178         CFG_MONITORING,
179         CFG_SERVERID,
180
181         CFG_LAST
182 };
183
184 typedef struct {
185         char *name, *oid;
186 } OidRec;
187
188 static OidRec OidMacros[] = {
189         /* OpenLDAProot:666.11.1 */
190         { "OLcfg", "1.3.6.1.4.1.4203.666.11.1" },
191         { "OLcfgAt", "OLcfg:3" },
192         { "OLcfgGlAt", "OLcfgAt:0" },
193         { "OLcfgBkAt", "OLcfgAt:1" },
194         { "OLcfgDbAt", "OLcfgAt:2" },
195         { "OLcfgOvAt", "OLcfgAt:3" },
196         { "OLcfgOc", "OLcfg:4" },
197         { "OLcfgGlOc", "OLcfgOc:0" },
198         { "OLcfgBkOc", "OLcfgOc:1" },
199         { "OLcfgDbOc", "OLcfgOc:2" },
200         { "OLcfgOvOc", "OLcfgOc:3" },
201
202         /* Syntaxes. We should just start using the standard names and
203          * document that they are predefined and available for users
204          * to reference in their own schema. Defining schema without
205          * OID macros is for masochists...
206          */
207         { "OMsyn", "1.3.6.1.4.1.1466.115.121.1" },
208         { "OMsBoolean", "OMsyn:7" },
209         { "OMsDN", "OMsyn:12" },
210         { "OMsDirectoryString", "OMsyn:15" },
211         { "OMsInteger", "OMsyn:27" },
212         { "OMsOID", "OMsyn:38" },
213         { "OMsOctetString", "OMsyn:40" },
214         { NULL, NULL }
215 };
216
217 /*
218  * Backend/Database registry
219  *
220  * OLcfg{Bk|Db}{Oc|At}:0                -> common
221  * OLcfg{Bk|Db}{Oc|At}:1                -> back-bdb(/back-hdb)
222  * OLcfg{Bk|Db}{Oc|At}:2                -> back-ldif
223  * OLcfg{Bk|Db}{Oc|At}:3                -> back-ldap
224  * OLcfg{Bk|Db}{Oc|At}:4                -> back-monitor
225  * OLcfg{Bk|Db}{Oc|At}:5                -> back-relay
226  * OLcfg{Bk|Db}{Oc|At}:6                -> back-sql
227  */
228
229 /*
230  * Overlay registry
231  *
232  * OLcfgOv{Oc|At}:1                     -> syncprov
233  * OLcfgOv{Oc|At}:2                     -> pcache
234  * OLcfgOv{Oc|At}:3                     -> chain
235  * OLcfgOv{Oc|At}:4                     -> accesslog
236  * OLcfgOv{Oc|At}:5                     -> valsort
237  * (FIXME: separate arc for contribware?)
238  * OLcfgOv{Oc|At}:6                     -> smbk5pwd
239  * OLcfgOv{Oc|At}:7                     -> distproc
240  * OLcfgOv{Oc|At}:8                     -> dynlist
241  * OLcfgOv{Oc|At}:9                     -> dds
242  * OLcfgOv{Oc|At}:10                    -> unique
243  * OLcfgOv{Oc|At}:11                    -> refint
244  * OLcfgOv{Oc|At}:12                    -> ppolicy
245  * OLcfgOv{Oc|At}:13                    -> constraint
246  * OLcfgOv{Oc|At}:14                    -> translucent
247  * OLcfgOv{Oc|At}:15                    -> auditlog
248  * OLcfgOv{Oc|At}:16                    -> rwm
249  * OLcfgOv{Oc|At}:17                    -> dyngroup
250  * OLcfgOv{Oc|At}:18                    -> memberof
251  * OLcfgOv{Oc|At}:19                    -> collect
252  */
253
254 /* alphabetical ordering */
255
256 static ConfigTable config_back_cf_table[] = {
257         /* This attr is read-only */
258         { "", "", 0, 0, 0, ARG_MAGIC,
259                 &config_fname, "( OLcfgGlAt:78 NAME 'olcConfigFile' "
260                         "DESC 'File for slapd configuration directives' "
261                         "EQUALITY caseIgnoreMatch "
262                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
263         { "", "", 0, 0, 0, ARG_MAGIC,
264                 &config_cfdir, "( OLcfgGlAt:79 NAME 'olcConfigDir' "
265                         "DESC 'Directory for slapd configuration backend' "
266                         "EQUALITY caseIgnoreMatch "
267                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
268         { "access",     NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC|CFG_ACL,
269                 &config_generic, "( OLcfgGlAt:1 NAME 'olcAccess' "
270                         "DESC 'Access Control List' "
271                         "EQUALITY caseIgnoreMatch "
272                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
273         { "allows",     "features", 2, 0, 5, ARG_PRE_DB|ARG_MAGIC,
274                 &config_allows, "( OLcfgGlAt:2 NAME 'olcAllows' "
275                         "DESC 'Allowed set of deprecated features' "
276                         "EQUALITY caseIgnoreMatch "
277                         "SYNTAX OMsDirectoryString )", NULL, NULL },
278         { "argsfile", "file", 2, 2, 0, ARG_STRING,
279                 &slapd_args_file, "( OLcfgGlAt:3 NAME 'olcArgsFile' "
280                         "DESC 'File for slapd command line options' "
281                         "EQUALITY caseIgnoreMatch "
282                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
283         { "attributeoptions", NULL, 0, 0, 0, ARG_MAGIC|CFG_ATOPT,
284                 &config_generic, "( OLcfgGlAt:5 NAME 'olcAttributeOptions' "
285                         "EQUALITY caseIgnoreMatch "
286                         "SYNTAX OMsDirectoryString )", NULL, NULL },
287         { "attribute",  "attribute", 2, 0, STRLENOF( "attribute" ),
288                 ARG_PAREN|ARG_MAGIC|CFG_ATTR,
289                 &config_generic, "( OLcfgGlAt:4 NAME 'olcAttributeTypes' "
290                         "DESC 'OpenLDAP attributeTypes' "
291                         "EQUALITY caseIgnoreMatch "
292                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
293                                 NULL, NULL },
294         { "authid-rewrite", NULL, 2, 0, STRLENOF( "authid-rewrite" ),
295 #ifdef SLAP_AUTH_REWRITE
296                 ARG_MAGIC|CFG_REWRITE|ARG_NO_INSERT, &config_generic,
297 #else
298                 ARG_IGNORED, NULL,
299 #endif
300                  "( OLcfgGlAt:6 NAME 'olcAuthIDRewrite' "
301                         "EQUALITY caseIgnoreMatch "
302                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
303         { "authz-policy", "policy", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_AZPOLICY,
304                 &config_generic, "( OLcfgGlAt:7 NAME 'olcAuthzPolicy' "
305                         "EQUALITY caseIgnoreMatch "
306                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
307         { "authz-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP|ARG_NO_INSERT,
308                 &config_generic, "( OLcfgGlAt:8 NAME 'olcAuthzRegexp' "
309                         "EQUALITY caseIgnoreMatch "
310                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
311         { "backend", "type", 2, 2, 0, ARG_PRE_DB|ARG_MAGIC|CFG_BACKEND,
312                 &config_generic, "( OLcfgGlAt:9 NAME 'olcBackend' "
313                         "DESC 'A type of backend' "
314                         "EQUALITY caseIgnoreMatch "
315                         "SYNTAX OMsDirectoryString SINGLE-VALUE X-ORDERED 'SIBLINGS' )",
316                                 NULL, NULL },
317         { "concurrency", "level", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_CONCUR,
318                 &config_generic, "( OLcfgGlAt:10 NAME 'olcConcurrency' "
319                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
320         { "conn_max_pending", "max", 2, 2, 0, ARG_INT,
321                 &slap_conn_max_pending, "( OLcfgGlAt:11 NAME 'olcConnMaxPending' "
322                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
323         { "conn_max_pending_auth", "max", 2, 2, 0, ARG_INT,
324                 &slap_conn_max_pending_auth, "( OLcfgGlAt:12 NAME 'olcConnMaxPendingAuth' "
325                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
326         { "database", "type", 2, 2, 0, ARG_MAGIC|CFG_DATABASE,
327                 &config_generic, "( OLcfgGlAt:13 NAME 'olcDatabase' "
328                         "DESC 'The backend type for a database instance' "
329                         "SUP olcBackend SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
330         { "defaultSearchBase", "dn", 2, 2, 0, ARG_PRE_BI|ARG_PRE_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
331                 &config_search_base, "( OLcfgGlAt:14 NAME 'olcDefaultSearchBase' "
332                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
333         { "disallows", "features", 2, 0, 8, ARG_PRE_DB|ARG_MAGIC,
334                 &config_disallows, "( OLcfgGlAt:15 NAME 'olcDisallows' "
335                         "EQUALITY caseIgnoreMatch "
336                         "SYNTAX OMsDirectoryString )", NULL, NULL },
337         { "ditcontentrule",     NULL, 0, 0, 0, ARG_MAGIC|CFG_DIT|ARG_NO_DELETE|ARG_NO_INSERT,
338                 &config_generic, "( OLcfgGlAt:16 NAME 'olcDitContentRules' "
339                         "DESC 'OpenLDAP DIT content rules' "
340                         "EQUALITY caseIgnoreMatch "
341                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
342                         NULL, NULL },
343         { "gentlehup", "on|off", 2, 2, 0,
344 #ifdef SIGHUP
345                 ARG_ON_OFF, &global_gentlehup,
346 #else
347                 ARG_IGNORED, NULL,
348 #endif
349                 "( OLcfgGlAt:17 NAME 'olcGentleHUP' "
350                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
351         { "hidden", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_HIDDEN,
352                 &config_generic, "( OLcfgDbAt:0.17 NAME 'olcHidden' "
353                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
354         { "idletimeout", "timeout", 2, 2, 0, ARG_INT,
355                 &global_idletimeout, "( OLcfgGlAt:18 NAME 'olcIdleTimeout' "
356                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
357         { "include", "file", 2, 2, 0, ARG_MAGIC,
358                 &config_include, "( OLcfgGlAt:19 NAME 'olcInclude' "
359                         "SUP labeledURI )", NULL, NULL },
360         { "index_substr_if_minlen", "min", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MIN,
361                 &config_generic, "( OLcfgGlAt:20 NAME 'olcIndexSubstrIfMinLen' "
362                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
363         { "index_substr_if_maxlen", "max", 2, 2, 0, ARG_INT|ARG_NONZERO|ARG_MAGIC|CFG_SSTR_IF_MAX,
364                 &config_generic, "( OLcfgGlAt:21 NAME 'olcIndexSubstrIfMaxLen' "
365                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
366         { "index_substr_any_len", "len", 2, 2, 0, ARG_INT|ARG_NONZERO,
367                 &index_substr_any_len, "( OLcfgGlAt:22 NAME 'olcIndexSubstrAnyLen' "
368                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
369         { "index_substr_any_step", "step", 2, 2, 0, ARG_INT|ARG_NONZERO,
370                 &index_substr_any_step, "( OLcfgGlAt:23 NAME 'olcIndexSubstrAnyStep' "
371                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
372         { "lastmod", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_LASTMOD,
373                 &config_generic, "( OLcfgDbAt:0.4 NAME 'olcLastMod' "
374                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
375         { "limits", "limits", 2, 0, 0, ARG_DB|ARG_MAGIC|CFG_LIMITS,
376                 &config_generic, "( OLcfgDbAt:0.5 NAME 'olcLimits' "
377                         "EQUALITY caseIgnoreMatch "
378                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
379         { "localSSF", "ssf", 2, 2, 0, ARG_INT,
380                 &local_ssf, "( OLcfgGlAt:26 NAME 'olcLocalSSF' "
381                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
382         { "logfile", "file", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_LOGFILE,
383                 &config_generic, "( OLcfgGlAt:27 NAME 'olcLogFile' "
384                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
385         { "loglevel", "level", 2, 0, 0, ARG_MAGIC,
386                 &config_loglevel, "( OLcfgGlAt:28 NAME 'olcLogLevel' "
387                         "EQUALITY caseIgnoreMatch "
388                         "SYNTAX OMsDirectoryString )", NULL, NULL },
389         { "maxDerefDepth", "depth", 2, 2, 0, ARG_DB|ARG_INT|ARG_MAGIC|CFG_DEPTH,
390                 &config_generic, "( OLcfgDbAt:0.6 NAME 'olcMaxDerefDepth' "
391                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
392         { "mirrormode", "on|off", 2, 2, 0, ARG_DB|ARG_ON_OFF|ARG_MAGIC|CFG_MIRRORMODE,
393                 &config_generic, "( OLcfgDbAt:0.16 NAME 'olcMirrorMode' "
394                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
395         { "moduleload", "file", 2, 0, 0,
396 #ifdef SLAPD_MODULES
397                 ARG_MAGIC|CFG_MODLOAD|ARG_NO_DELETE, &config_generic,
398 #else
399                 ARG_IGNORED, NULL,
400 #endif
401                 "( OLcfgGlAt:30 NAME 'olcModuleLoad' "
402                         "EQUALITY caseIgnoreMatch "
403                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
404         { "modulepath", "path", 2, 2, 0,
405 #ifdef SLAPD_MODULES
406                 ARG_MAGIC|CFG_MODPATH|ARG_NO_DELETE|ARG_NO_INSERT, &config_generic,
407 #else
408                 ARG_IGNORED, NULL,
409 #endif
410                 "( OLcfgGlAt:31 NAME 'olcModulePath' "
411                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
412         { "monitoring", "TRUE|FALSE", 2, 2, 0,
413                 ARG_MAGIC|CFG_MONITORING|ARG_DB|ARG_ON_OFF, &config_generic,
414                 "( OLcfgDbAt:0.18 NAME 'olcMonitoring' "
415                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
416         { "objectclass", "objectclass", 2, 0, 0, ARG_PAREN|ARG_MAGIC|CFG_OC,
417                 &config_generic, "( OLcfgGlAt:32 NAME 'olcObjectClasses' "
418                 "DESC 'OpenLDAP object classes' "
419                 "EQUALITY caseIgnoreMatch "
420                 "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )",
421                         NULL, NULL },
422         { "objectidentifier", "name> <oid",     3, 3, 0, ARG_MAGIC|CFG_OID,
423                 &config_generic, "( OLcfgGlAt:33 NAME 'olcObjectIdentifier' "
424                         "EQUALITY caseIgnoreMatch "
425                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
426         { "overlay", "overlay", 2, 2, 0, ARG_MAGIC,
427                 &config_overlay, "( OLcfgGlAt:34 NAME 'olcOverlay' "
428                         "SUP olcDatabase SINGLE-VALUE X-ORDERED 'SIBLINGS' )", NULL, NULL },
429         { "password-crypt-salt-format", "salt", 2, 2, 0, ARG_STRING|ARG_MAGIC|CFG_SALT,
430                 &config_generic, "( OLcfgGlAt:35 NAME 'olcPasswordCryptSaltFormat' "
431                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
432         { "password-hash", "hash", 2, 2, 0, ARG_MAGIC,
433                 &config_passwd_hash, "( OLcfgGlAt:36 NAME 'olcPasswordHash' "
434                         "EQUALITY caseIgnoreMatch "
435                         "SYNTAX OMsDirectoryString )", NULL, NULL },
436         { "pidfile", "file", 2, 2, 0, ARG_STRING,
437                 &slapd_pid_file, "( OLcfgGlAt:37 NAME 'olcPidFile' "
438                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
439         { "plugin", NULL, 0, 0, 0,
440 #ifdef LDAP_SLAPI
441                 ARG_MAGIC|CFG_PLUGIN, &config_generic,
442 #else
443                 ARG_IGNORED, NULL,
444 #endif
445                 "( OLcfgGlAt:38 NAME 'olcPlugin' "
446                         "EQUALITY caseIgnoreMatch "
447                         "SYNTAX OMsDirectoryString )", NULL, NULL },
448         { "pluginlog", "filename", 2, 2, 0,
449 #ifdef LDAP_SLAPI
450                 ARG_STRING, &slapi_log_file,
451 #else
452                 ARG_IGNORED, NULL,
453 #endif
454                 "( OLcfgGlAt:39 NAME 'olcPluginLogFile' "
455                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
456         { "readonly", "on|off", 2, 2, 0, ARG_MAY_DB|ARG_ON_OFF|ARG_MAGIC|CFG_RO,
457                 &config_generic, "( OLcfgGlAt:40 NAME 'olcReadOnly' "
458                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
459         { "referral", "url", 2, 2, 0, ARG_MAGIC,
460                 &config_referral, "( OLcfgGlAt:41 NAME 'olcReferral' "
461                         "SUP labeledURI SINGLE-VALUE )", NULL, NULL },
462         { "replica", "host or uri", 2, 0, 0, ARG_DB|ARG_MAGIC,
463                 &config_obsolete, "( OLcfgDbAt:0.7 NAME 'olcReplica' "
464                         "EQUALITY caseIgnoreMatch "
465                         "SUP labeledURI X-ORDERED 'VALUES' )", NULL, NULL },
466         { "replica-argsfile", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
467                 &config_obsolete, "( OLcfgGlAt:43 NAME 'olcReplicaArgsFile' "
468                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
469         { "replica-pidfile", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
470                 &config_obsolete, "( OLcfgGlAt:44 NAME 'olcReplicaPidFile' "
471                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
472         { "replicationInterval", NULL, 0, 0, 0, ARG_MAY_DB|ARG_MAGIC,
473                 &config_obsolete, "( OLcfgGlAt:45 NAME 'olcReplicationInterval' "
474                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
475         { "replogfile", "filename", 2, 2, 0, ARG_MAY_DB|ARG_MAGIC,
476                 &config_obsolete, "( OLcfgGlAt:46 NAME 'olcReplogFile' "
477                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
478         { "require", "features", 2, 0, 7, ARG_MAY_DB|ARG_MAGIC,
479                 &config_requires, "( OLcfgGlAt:47 NAME 'olcRequires' "
480                         "EQUALITY caseIgnoreMatch "
481                         "SYNTAX OMsDirectoryString )", NULL, NULL },
482         { "restrict", "op_list", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
483                 &config_restrict, "( OLcfgGlAt:48 NAME 'olcRestrict' "
484                         "EQUALITY caseIgnoreMatch "
485                         "SYNTAX OMsDirectoryString )", NULL, NULL },
486         { "reverse-lookup", "on|off", 2, 2, 0,
487 #ifdef SLAPD_RLOOKUPS
488                 ARG_ON_OFF, &use_reverse_lookup,
489 #else
490                 ARG_IGNORED, NULL,
491 #endif
492                 "( OLcfgGlAt:49 NAME 'olcReverseLookup' "
493                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
494         { "rootdn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
495                 &config_rootdn, "( OLcfgDbAt:0.8 NAME 'olcRootDN' "
496                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
497         { "rootDSE", "file", 2, 2, 0, ARG_MAGIC|CFG_ROOTDSE,
498                 &config_generic, "( OLcfgGlAt:51 NAME 'olcRootDSE' "
499                         "EQUALITY caseIgnoreMatch "
500                         "SYNTAX OMsDirectoryString )", NULL, NULL },
501         { "rootpw", "password", 2, 2, 0, ARG_BERVAL|ARG_DB|ARG_MAGIC,
502                 &config_rootpw, "( OLcfgDbAt:0.9 NAME 'olcRootPW' "
503                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
504         { "sasl-authz-policy", NULL, 2, 2, 0, ARG_MAGIC|CFG_AZPOLICY,
505                 &config_generic, NULL, NULL, NULL },
506         { "sasl-host", "host", 2, 2, 0,
507 #ifdef HAVE_CYRUS_SASL
508                 ARG_STRING|ARG_UNIQUE, &global_host,
509 #else
510                 ARG_IGNORED, NULL,
511 #endif
512                 "( OLcfgGlAt:53 NAME 'olcSaslHost' "
513                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
514         { "sasl-realm", "realm", 2, 2, 0,
515 #ifdef HAVE_CYRUS_SASL
516                 ARG_STRING|ARG_UNIQUE, &global_realm,
517 #else
518                 ARG_IGNORED, NULL,
519 #endif
520                 "( OLcfgGlAt:54 NAME 'olcSaslRealm' "
521                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
522         { "sasl-regexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
523                 &config_generic, NULL, NULL, NULL },
524         { "sasl-secprops", "properties", 2, 2, 0,
525 #ifdef HAVE_CYRUS_SASL
526                 ARG_MAGIC|CFG_SASLSECP, &config_generic,
527 #else
528                 ARG_IGNORED, NULL,
529 #endif
530                 "( OLcfgGlAt:56 NAME 'olcSaslSecProps' "
531                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
532         { "saslRegexp", NULL, 3, 3, 0, ARG_MAGIC|CFG_AZREGEXP,
533                 &config_generic, NULL, NULL, NULL },
534         { "schemadn", "dn", 2, 2, 0, ARG_MAY_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
535                 &config_schema_dn, "( OLcfgGlAt:58 NAME 'olcSchemaDN' "
536                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
537         { "security", "factors", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
538                 &config_security, "( OLcfgGlAt:59 NAME 'olcSecurity' "
539                         "EQUALITY caseIgnoreMatch "
540                         "SYNTAX OMsDirectoryString )", NULL, NULL },
541         { "serverID", "number> <[URI]", 2, 3, 0, ARG_MAGIC|CFG_SERVERID,
542                 &config_generic, "( OLcfgGlAt:81 NAME 'olcServerID' "
543                         "EQUALITY caseIgnoreMatch "
544                         "SYNTAX OMsDirectoryString )", NULL, NULL },
545         { "sizelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
546                 &config_sizelimit, "( OLcfgGlAt:60 NAME 'olcSizeLimit' "
547                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
548         { "sockbuf_max_incoming", "max", 2, 2, 0, ARG_BER_LEN_T,
549                 &sockbuf_max_incoming, "( OLcfgGlAt:61 NAME 'olcSockbufMaxIncoming' "
550                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
551         { "sockbuf_max_incoming_auth", "max", 2, 2, 0, ARG_BER_LEN_T,
552                 &sockbuf_max_incoming_auth, "( OLcfgGlAt:62 NAME 'olcSockbufMaxIncomingAuth' "
553                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
554         { "subordinate", "[advertise]", 1, 2, 0, ARG_DB|ARG_MAGIC,
555                 &config_subordinate, "( OLcfgDbAt:0.15 NAME 'olcSubordinate' "
556                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
557         { "suffix",     "suffix", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
558                 &config_suffix, "( OLcfgDbAt:0.10 NAME 'olcSuffix' "
559                         "EQUALITY distinguishedNameMatch "
560                         "SYNTAX OMsDN )", NULL, NULL },
561         { "syncrepl", NULL, 0, 0, 0, ARG_DB|ARG_MAGIC,
562                 &syncrepl_config, "( OLcfgDbAt:0.11 NAME 'olcSyncrepl' "
563                         "EQUALITY caseIgnoreMatch "
564                         "SYNTAX OMsDirectoryString X-ORDERED 'VALUES' )", NULL, NULL },
565         { "threads", "count", 2, 2, 0,
566 #ifdef NO_THREADS
567                 ARG_IGNORED, NULL,
568 #else
569                 ARG_INT|ARG_MAGIC|CFG_THREADS, &config_generic,
570 #endif
571                 "( OLcfgGlAt:66 NAME 'olcThreads' "
572                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
573         { "timelimit", "limit", 2, 0, 0, ARG_MAY_DB|ARG_MAGIC,
574                 &config_timelimit, "( OLcfgGlAt:67 NAME 'olcTimeLimit' "
575                         "SYNTAX OMsDirectoryString )", NULL, NULL },
576         { "TLSCACertificateFile", NULL, 0, 0, 0,
577 #ifdef HAVE_TLS
578                 CFG_TLS_CA_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
579 #else
580                 ARG_IGNORED, NULL,
581 #endif
582                 "( OLcfgGlAt:68 NAME 'olcTLSCACertificateFile' "
583                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
584         { "TLSCACertificatePath", NULL, 0, 0, 0,
585 #ifdef HAVE_TLS
586                 CFG_TLS_CA_PATH|ARG_STRING|ARG_MAGIC, &config_tls_option,
587 #else
588                 ARG_IGNORED, NULL,
589 #endif
590                 "( OLcfgGlAt:69 NAME 'olcTLSCACertificatePath' "
591                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
592         { "TLSCertificateFile", NULL, 0, 0, 0,
593 #ifdef HAVE_TLS
594                 CFG_TLS_CERT_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
595 #else
596                 ARG_IGNORED, NULL,
597 #endif
598                 "( OLcfgGlAt:70 NAME 'olcTLSCertificateFile' "
599                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
600         { "TLSCertificateKeyFile", NULL, 0, 0, 0,
601 #ifdef HAVE_TLS
602                 CFG_TLS_CERT_KEY|ARG_STRING|ARG_MAGIC, &config_tls_option,
603 #else
604                 ARG_IGNORED, NULL,
605 #endif
606                 "( OLcfgGlAt:71 NAME 'olcTLSCertificateKeyFile' "
607                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
608         { "TLSCipherSuite",     NULL, 0, 0, 0,
609 #ifdef HAVE_TLS
610                 CFG_TLS_CIPHER|ARG_STRING|ARG_MAGIC, &config_tls_option,
611 #else
612                 ARG_IGNORED, NULL,
613 #endif
614                 "( OLcfgGlAt:72 NAME 'olcTLSCipherSuite' "
615                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
616         { "TLSCRLCheck", NULL, 0, 0, 0,
617 #if defined(HAVE_TLS) && defined(HAVE_OPENSSL_CRL)
618                 CFG_TLS_CRLCHECK|ARG_STRING|ARG_MAGIC, &config_tls_config,
619 #else
620                 ARG_IGNORED, NULL,
621 #endif
622                 "( OLcfgGlAt:73 NAME 'olcTLSCRLCheck' "
623                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
624         { "TLSCRLFile", NULL, 0, 0, 0,
625 #if defined(HAVE_GNUTLS)
626                 CFG_TLS_CRL_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
627 #else
628                 ARG_IGNORED, NULL,
629 #endif
630                 "( OLcfgGlAt:82 NAME 'olcTLSCRLFile' "
631                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
632         { "TLSRandFile", NULL, 0, 0, 0,
633 #ifdef HAVE_TLS
634                 CFG_TLS_RAND|ARG_STRING|ARG_MAGIC, &config_tls_option,
635 #else
636                 ARG_IGNORED, NULL,
637 #endif
638                 "( OLcfgGlAt:74 NAME 'olcTLSRandFile' "
639                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
640         { "TLSVerifyClient", NULL, 0, 0, 0,
641 #ifdef HAVE_TLS
642                 CFG_TLS_VERIFY|ARG_STRING|ARG_MAGIC, &config_tls_config,
643 #else
644                 ARG_IGNORED, NULL,
645 #endif
646                 "( OLcfgGlAt:75 NAME 'olcTLSVerifyClient' "
647                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
648         { "TLSDHParamFile", NULL, 0, 0, 0,
649 #ifdef HAVE_TLS
650                 CFG_TLS_DH_FILE|ARG_STRING|ARG_MAGIC, &config_tls_option,
651 #else
652                 ARG_IGNORED, NULL,
653 #endif
654                 "( OLcfgGlAt:77 NAME 'olcTLSDHParamFile' "
655                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
656         { "tool-threads", "count", 2, 2, 0, ARG_INT|ARG_MAGIC|CFG_TTHREADS,
657                 &config_generic, "( OLcfgGlAt:80 NAME 'olcToolThreads' "
658                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
659         { "ucdata-path", "path", 2, 2, 0, ARG_IGNORED,
660                 NULL, NULL, NULL, NULL },
661         { "updatedn", "dn", 2, 2, 0, ARG_DB|ARG_DN|ARG_QUOTE|ARG_MAGIC,
662                 &config_updatedn, "( OLcfgDbAt:0.12 NAME 'olcUpdateDN' "
663                         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
664         { "updateref", "url", 2, 2, 0, ARG_DB|ARG_MAGIC,
665                 &config_updateref, "( OLcfgDbAt:0.13 NAME 'olcUpdateRef' "
666                         "EQUALITY caseIgnoreMatch "
667                         "SUP labeledURI )", NULL, NULL },
668         { NULL, NULL, 0, 0, 0, ARG_IGNORED,
669                 NULL, NULL, NULL, NULL }
670 };
671
672 /* Routines to check if a child can be added to this type */
673 static ConfigLDAPadd cfAddSchema, cfAddInclude, cfAddDatabase,
674         cfAddBackend, cfAddModule, cfAddOverlay;
675
676 /* NOTE: be careful when defining array members
677  * that can be conditionally compiled */
678 #define CFOC_GLOBAL     cf_ocs[1]
679 #define CFOC_SCHEMA     cf_ocs[2]
680 #define CFOC_BACKEND    cf_ocs[3]
681 #define CFOC_DATABASE   cf_ocs[4]
682 #define CFOC_OVERLAY    cf_ocs[5]
683 #define CFOC_INCLUDE    cf_ocs[6]
684 #define CFOC_FRONTEND   cf_ocs[7]
685 #ifdef SLAPD_MODULES
686 #define CFOC_MODULE     cf_ocs[8]
687 #endif /* SLAPD_MODULES */
688
689 static ConfigOCs cf_ocs[] = {
690         { "( OLcfgGlOc:0 "
691                 "NAME 'olcConfig' "
692                 "DESC 'OpenLDAP configuration object' "
693                 "ABSTRACT SUP top )", Cft_Abstract, NULL },
694         { "( OLcfgGlOc:1 "
695                 "NAME 'olcGlobal' "
696                 "DESC 'OpenLDAP Global configuration options' "
697                 "SUP olcConfig STRUCTURAL "
698                 "MAY ( cn $ olcConfigFile $ olcConfigDir $ olcAllows $ olcArgsFile $ "
699                  "olcAttributeOptions $ olcAuthIDRewrite $ "
700                  "olcAuthzPolicy $ olcAuthzRegexp $ olcConcurrency $ "
701                  "olcConnMaxPending $ olcConnMaxPendingAuth $ "
702                  "olcDisallows $ olcGentleHUP $ olcIdleTimeout $ "
703                  "olcIndexSubstrIfMaxLen $ olcIndexSubstrIfMinLen $ "
704                  "olcIndexSubstrAnyLen $ olcIndexSubstrAnyStep $ olcLocalSSF $ "
705                  "olcLogLevel $ "
706                  "olcPasswordCryptSaltFormat $ olcPidFile $ "
707                  "olcPluginLogFile $ olcReadOnly $ olcReferral $ "
708                  "olcReplogFile $ olcRequires $ olcRestrict $ olcReverseLookup $ "
709                  "olcRootDSE $ "
710                  "olcSaslHost $ olcSaslRealm $ olcSaslSecProps $ "
711                  "olcSecurity $ olcServerID $ olcSizeLimit $ "
712                  "olcSockbufMaxIncoming $ olcSockbufMaxIncomingAuth $ "
713                  "olcThreads $ olcTimeLimit $ olcTLSCACertificateFile $ "
714                  "olcTLSCACertificatePath $ olcTLSCertificateFile $ "
715                  "olcTLSCertificateKeyFile $ olcTLSCipherSuite $ olcTLSCRLCheck $ "
716                  "olcTLSRandFile $ olcTLSVerifyClient $ olcTLSDHParamFile $ "
717                  "olcTLSCRLFile $ olcToolThreads $ "
718                  "olcObjectIdentifier $ olcAttributeTypes $ olcObjectClasses $ "
719                  "olcDitContentRules ) )", Cft_Global },
720         { "( OLcfgGlOc:2 "
721                 "NAME 'olcSchemaConfig' "
722                 "DESC 'OpenLDAP schema object' "
723                 "SUP olcConfig STRUCTURAL "
724                 "MAY ( cn $ olcObjectIdentifier $ olcAttributeTypes $ "
725                  "olcObjectClasses $ olcDitContentRules ) )",
726                         Cft_Schema, NULL, cfAddSchema },
727         { "( OLcfgGlOc:3 "
728                 "NAME 'olcBackendConfig' "
729                 "DESC 'OpenLDAP Backend-specific options' "
730                 "SUP olcConfig STRUCTURAL "
731                 "MUST olcBackend )", Cft_Backend, NULL, cfAddBackend },
732         { "( OLcfgGlOc:4 "
733                 "NAME 'olcDatabaseConfig' "
734                 "DESC 'OpenLDAP Database-specific options' "
735                 "SUP olcConfig STRUCTURAL "
736                 "MUST olcDatabase "
737                 "MAY ( olcHidden $ olcSuffix $ olcSubordinate $ olcAccess $ "
738                  "olcLastMod $ olcLimits $ "
739                  "olcMaxDerefDepth $ olcPlugin $ olcReadOnly $ olcReplica $ "
740                  "olcReplicaArgsFile $ olcReplicaPidFile $ olcReplicationInterval $ "
741                  "olcReplogFile $ olcRequires $ olcRestrict $ olcRootDN $ olcRootPW $ "
742                  "olcSchemaDN $ olcSecurity $ olcSizeLimit $ olcSyncrepl $ "
743                  "olcTimeLimit $ olcUpdateDN $ olcUpdateRef $ olcMirrorMode $ "
744                  "olcMonitoring ) )",
745                         Cft_Database, NULL, cfAddDatabase },
746         { "( OLcfgGlOc:5 "
747                 "NAME 'olcOverlayConfig' "
748                 "DESC 'OpenLDAP Overlay-specific options' "
749                 "SUP olcConfig STRUCTURAL "
750                 "MUST olcOverlay )", Cft_Overlay, NULL, cfAddOverlay },
751         { "( OLcfgGlOc:6 "
752                 "NAME 'olcIncludeFile' "
753                 "DESC 'OpenLDAP configuration include file' "
754                 "SUP olcConfig STRUCTURAL "
755                 "MUST olcInclude "
756                 "MAY ( cn $ olcRootDSE ) )",
757                 /* Used to be Cft_Include, that def has been removed */
758                 Cft_Abstract, NULL, cfAddInclude },
759         /* This should be STRUCTURAL like all the other database classes, but
760          * that would mean inheriting all of the olcDatabaseConfig attributes,
761          * which causes them to be merged twice in config_build_entry.
762          */
763         { "( OLcfgGlOc:7 "
764                 "NAME 'olcFrontendConfig' "
765                 "DESC 'OpenLDAP frontend configuration' "
766                 "AUXILIARY "
767                 "MAY ( olcDefaultSearchBase $ olcPasswordHash ) )",
768                 Cft_Database, NULL, NULL },
769 #ifdef SLAPD_MODULES
770         { "( OLcfgGlOc:8 "
771                 "NAME 'olcModuleList' "
772                 "DESC 'OpenLDAP dynamic module info' "
773                 "SUP olcConfig STRUCTURAL "
774                 "MAY ( cn $ olcModulePath $ olcModuleLoad ) )",
775                 Cft_Module, NULL, cfAddModule },
776 #endif
777         { NULL, 0, NULL }
778 };
779
780 typedef struct ServerID {
781         struct ServerID *si_next;
782         struct berval si_url;
783         int si_num;
784 } ServerID;
785
786 static ServerID *sid_list;
787
788 static int
789 config_generic(ConfigArgs *c) {
790         int i;
791
792         if ( c->op == SLAP_CONFIG_EMIT ) {
793                 int rc = 0;
794                 switch(c->type) {
795                 case CFG_CONCUR:
796                         c->value_int = ldap_pvt_thread_get_concurrency();
797                         break;
798                 case CFG_THREADS:
799                         c->value_int = connection_pool_max;
800                         break;
801                 case CFG_TTHREADS:
802                         c->value_int = slap_tool_thread_max;
803                         break;
804                 case CFG_SALT:
805                         if ( passwd_salt )
806                                 c->value_string = ch_strdup( passwd_salt );
807                         else
808                                 rc = 1;
809                         break;
810                 case CFG_LIMITS:
811                         if ( c->be->be_limits ) {
812                                 char buf[4096*3];
813                                 struct berval bv;
814
815                                 for ( i=0; c->be->be_limits[i]; i++ ) {
816                                         bv.bv_len = snprintf( buf, sizeof( buf ), SLAP_X_ORDERED_FMT, i );
817                                         if ( bv.bv_len >= sizeof( buf ) ) {
818                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
819                                                 c->rvalue_vals = NULL;
820                                                 rc = 1;
821                                                 break;
822                                         }
823                                         bv.bv_val = buf + bv.bv_len;
824                                         limits_unparse( c->be->be_limits[i], &bv,
825                                                         sizeof( buf ) - ( bv.bv_val - buf ) );
826                                         bv.bv_len += bv.bv_val - buf;
827                                         bv.bv_val = buf;
828                                         value_add_one( &c->rvalue_vals, &bv );
829                                 }
830                         }
831                         if ( !c->rvalue_vals ) rc = 1;
832                         break;
833                 case CFG_RO:
834                         c->value_int = (c->be->be_restrictops & SLAP_RESTRICT_OP_WRITES) ==
835                                 SLAP_RESTRICT_OP_WRITES;
836                         break;
837                 case CFG_AZPOLICY:
838                         c->value_string = ch_strdup( slap_sasl_getpolicy());
839                         break;
840                 case CFG_AZREGEXP:
841                         slap_sasl_regexp_unparse( &c->rvalue_vals );
842                         if ( !c->rvalue_vals ) rc = 1;
843                         break;
844 #ifdef HAVE_CYRUS_SASL
845                 case CFG_SASLSECP: {
846                         struct berval bv = BER_BVNULL;
847                         slap_sasl_secprops_unparse( &bv );
848                         if ( !BER_BVISNULL( &bv )) {
849                                 ber_bvarray_add( &c->rvalue_vals, &bv );
850                         } else {
851                                 rc = 1;
852                         }
853                         }
854                         break;
855 #endif
856                 case CFG_DEPTH:
857                         c->value_int = c->be->be_max_deref_depth;
858                         break;
859                 case CFG_HIDDEN:
860                         if ( SLAP_DBHIDDEN( c->be )) {
861                                 c->value_int = 1;
862                         } else {
863                                 rc = 1;
864                         }
865                         break;
866                 case CFG_OID: {
867                         ConfigFile *cf = c->private;
868                         if ( !cf )
869                                 oidm_unparse( &c->rvalue_vals, NULL, NULL, 1 );
870                         else if ( cf->c_om_head )
871                                 oidm_unparse( &c->rvalue_vals, cf->c_om_head,
872                                         cf->c_om_tail, 0 );
873                         if ( !c->rvalue_vals )
874                                 rc = 1;
875                         }
876                         break;
877                 case CFG_ATOPT:
878                         ad_unparse_options( &c->rvalue_vals );
879                         break;
880                 case CFG_OC: {
881                         ConfigFile *cf = c->private;
882                         if ( !cf )
883                                 oc_unparse( &c->rvalue_vals, NULL, NULL, 1 );
884                         else if ( cf->c_oc_head )
885                                 oc_unparse( &c->rvalue_vals, cf->c_oc_head,
886                                         cf->c_oc_tail, 0 );
887                         if ( !c->rvalue_vals )
888                                 rc = 1;
889                         }
890                         break;
891                 case CFG_ATTR: {
892                         ConfigFile *cf = c->private;
893                         if ( !cf )
894                                 at_unparse( &c->rvalue_vals, NULL, NULL, 1 );
895                         else if ( cf->c_at_head )
896                                 at_unparse( &c->rvalue_vals, cf->c_at_head,
897                                         cf->c_at_tail, 0 );
898                         if ( !c->rvalue_vals )
899                                 rc = 1;
900                         }
901                         break;
902                 case CFG_DIT: {
903                         ConfigFile *cf = c->private;
904                         if ( !cf )
905                                 cr_unparse( &c->rvalue_vals, NULL, NULL, 1 );
906                         else if ( cf->c_cr_head )
907                                 cr_unparse( &c->rvalue_vals, cf->c_cr_head,
908                                         cf->c_cr_tail, 0 );
909                         if ( !c->rvalue_vals )
910                                 rc = 1;
911                         }
912                         break;
913                         
914                 case CFG_ACL: {
915                         AccessControl *a;
916                         char *src, *dst, ibuf[11];
917                         struct berval bv, abv;
918                         for (i=0, a=c->be->be_acl; a; i++,a=a->acl_next) {
919                                 abv.bv_len = snprintf( ibuf, sizeof( ibuf ), SLAP_X_ORDERED_FMT, i );
920                                 if ( abv.bv_len >= sizeof( ibuf ) ) {
921                                         ber_bvarray_free_x( c->rvalue_vals, NULL );
922                                         c->rvalue_vals = NULL;
923                                         i = 0;
924                                         break;
925                                 }
926                                 acl_unparse( a, &bv );
927                                 abv.bv_val = ch_malloc( abv.bv_len + bv.bv_len + 1 );
928                                 AC_MEMCPY( abv.bv_val, ibuf, abv.bv_len );
929                                 /* Turn TAB / EOL into plain space */
930                                 for (src=bv.bv_val,dst=abv.bv_val+abv.bv_len; *src; src++) {
931                                         if (isspace((unsigned char)*src)) *dst++ = ' ';
932                                         else *dst++ = *src;
933                                 }
934                                 *dst = '\0';
935                                 if (dst[-1] == ' ') {
936                                         dst--;
937                                         *dst = '\0';
938                                 }
939                                 abv.bv_len = dst - abv.bv_val;
940                                 ber_bvarray_add( &c->rvalue_vals, &abv );
941                         }
942                         rc = (!i);
943                         break;
944                 }
945                 case CFG_ROOTDSE: {
946                         ConfigFile *cf = c->private;
947                         if ( cf->c_dseFiles ) {
948                                 value_add( &c->rvalue_vals, cf->c_dseFiles );
949                         } else {
950                                 rc = 1;
951                         }
952                         }
953                         break;
954                 case CFG_SERVERID:
955                         if ( sid_list ) {
956                                 ServerID *si;
957                                 struct berval bv;
958
959                                 for ( si = sid_list; si; si=si->si_next ) {
960                                         assert( si->si_num >= 0 && si->si_num <= SLAP_SYNC_SID_MAX );
961                                         if ( !BER_BVISEMPTY( &si->si_url )) {
962                                                 bv.bv_len = si->si_url.bv_len + 6;
963                                                 bv.bv_val = ch_malloc( bv.bv_len );
964                                                 sprintf( bv.bv_val, "%d %s", si->si_num,
965                                                         si->si_url.bv_val );
966                                                 ber_bvarray_add( &c->rvalue_vals, &bv );
967                                         } else {
968                                                 char buf[5];
969                                                 bv.bv_val = buf;
970                                                 bv.bv_len = sprintf( buf, "%d", si->si_num );
971                                                 value_add_one( &c->rvalue_vals, &bv );
972                                         }
973                                 }
974                         } else {
975                                 rc = 1;
976                         }
977                         break;
978                 case CFG_LOGFILE:
979                         if ( logfileName )
980                                 c->value_string = ch_strdup( logfileName );
981                         else
982                                 rc = 1;
983                         break;
984                 case CFG_LASTMOD:
985                         c->value_int = (SLAP_NOLASTMOD(c->be) == 0);
986                         break;
987                 case CFG_MIRRORMODE:
988                         if ( SLAP_SHADOW(c->be))
989                                 c->value_int = (SLAP_SINGLE_SHADOW(c->be) == 0);
990                         else
991                                 rc = 1;
992                         break;
993                 case CFG_MONITORING:
994                         c->value_int = (SLAP_DBMONITORING(c->be) != 0);
995                         break;
996                 case CFG_SSTR_IF_MAX:
997                         c->value_int = index_substr_if_maxlen;
998                         break;
999                 case CFG_SSTR_IF_MIN:
1000                         c->value_int = index_substr_if_minlen;
1001                         break;
1002 #ifdef SLAPD_MODULES
1003                 case CFG_MODLOAD: {
1004                         ModPaths *mp = c->private;
1005                         if (mp->mp_loads) {
1006                                 int i;
1007                                 for (i=0; !BER_BVISNULL(&mp->mp_loads[i]); i++) {
1008                                         struct berval bv;
1009                                         bv.bv_val = c->log;
1010                                         bv.bv_len = snprintf( bv.bv_val, sizeof( c->log ),
1011                                                 SLAP_X_ORDERED_FMT "%s", i,
1012                                                 mp->mp_loads[i].bv_val );
1013                                         if ( bv.bv_len >= sizeof( c->log ) ) {
1014                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
1015                                                 c->rvalue_vals = NULL;
1016                                                 break;
1017                                         }
1018                                         value_add_one( &c->rvalue_vals, &bv );
1019                                 }
1020                         }
1021
1022                         rc = c->rvalue_vals ? 0 : 1;
1023                         }
1024                         break;
1025                 case CFG_MODPATH: {
1026                         ModPaths *mp = c->private;
1027                         if ( !BER_BVISNULL( &mp->mp_path ))
1028                                 value_add_one( &c->rvalue_vals, &mp->mp_path );
1029
1030                         rc = c->rvalue_vals ? 0 : 1;
1031                         }
1032                         break;
1033 #endif
1034 #ifdef LDAP_SLAPI
1035                 case CFG_PLUGIN:
1036                         slapi_int_plugin_unparse( c->be, &c->rvalue_vals );
1037                         if ( !c->rvalue_vals ) rc = 1;
1038                         break;
1039 #endif
1040 #ifdef SLAP_AUTH_REWRITE
1041                 case CFG_REWRITE:
1042                         if ( authz_rewrites ) {
1043                                 struct berval bv, idx;
1044                                 char ibuf[32];
1045                                 int i;
1046
1047                                 idx.bv_val = ibuf;
1048                                 for ( i=0; !BER_BVISNULL( &authz_rewrites[i] ); i++ ) {
1049                                         idx.bv_len = snprintf( idx.bv_val, sizeof( ibuf ), SLAP_X_ORDERED_FMT, i );
1050                                         if ( idx.bv_len >= sizeof( ibuf ) ) {
1051                                                 ber_bvarray_free_x( c->rvalue_vals, NULL );
1052                                                 c->rvalue_vals = NULL;
1053                                                 break;
1054                                         }
1055                                         bv.bv_len = idx.bv_len + authz_rewrites[i].bv_len;
1056                                         bv.bv_val = ch_malloc( bv.bv_len + 1 );
1057                                         AC_MEMCPY( bv.bv_val, idx.bv_val, idx.bv_len );
1058                                         AC_MEMCPY( &bv.bv_val[ idx.bv_len ],
1059                                                 authz_rewrites[i].bv_val,
1060                                                 authz_rewrites[i].bv_len + 1 );
1061                                         ber_bvarray_add( &c->rvalue_vals, &bv );
1062                                 }
1063                         }
1064                         if ( !c->rvalue_vals ) rc = 1;
1065                         break;
1066 #endif
1067                 default:
1068                         rc = 1;
1069                 }
1070                 return rc;
1071         } else if ( c->op == LDAP_MOD_DELETE ) {
1072                 int rc = 0;
1073                 switch(c->type) {
1074                 /* single-valued attrs, no-ops */
1075                 case CFG_CONCUR:
1076                 case CFG_THREADS:
1077                 case CFG_TTHREADS:
1078                 case CFG_RO:
1079                 case CFG_AZPOLICY:
1080                 case CFG_DEPTH:
1081                 case CFG_LASTMOD:
1082                 case CFG_MIRRORMODE:
1083                 case CFG_MONITORING:
1084                 case CFG_SASLSECP:
1085                 case CFG_SSTR_IF_MAX:
1086                 case CFG_SSTR_IF_MIN:
1087                         break;
1088
1089                 /* no-ops, requires slapd restart */
1090                 case CFG_PLUGIN:
1091                 case CFG_MODLOAD:
1092                 case CFG_AZREGEXP:
1093                 case CFG_REWRITE:
1094                         snprintf(c->log, sizeof( c->log ), "change requires slapd restart");
1095                         break;
1096
1097                 case CFG_SALT:
1098                         ch_free( passwd_salt );
1099                         passwd_salt = NULL;
1100                         break;
1101
1102                 case CFG_LOGFILE:
1103                         ch_free( logfileName );
1104                         logfileName = NULL;
1105                         break;
1106
1107                 case CFG_SERVERID: {
1108                         ServerID *si, **sip;
1109
1110                         for ( i=0, si = sid_list, sip = &sid_list;
1111                                 si; si = *sip, i++ ) {
1112                                 if ( c->valx == -1 || i == c->valx ) {
1113                                         *sip = si->si_next;
1114                                         ch_free( si );
1115                                         if ( c->valx >= 0 )
1116                                                 break;
1117                                 } else {
1118                                         sip = &si->si_next;
1119                                 }
1120                         }
1121                         }
1122                         break;
1123                 case CFG_HIDDEN:
1124                         c->be->be_flags &= ~SLAP_DBFLAG_HIDDEN;
1125                         break;
1126
1127                 case CFG_ACL:
1128                         if ( c->valx < 0 ) {
1129                                 AccessControl *end;
1130                                 if ( c->be == frontendDB )
1131                                         end = NULL;
1132                                 else
1133                                         end = frontendDB->be_acl;
1134                                 acl_destroy( c->be->be_acl, end );
1135                                 c->be->be_acl = end;
1136
1137                         } else {
1138                                 AccessControl **prev, *a;
1139                                 int i;
1140                                 for (i=0, prev = &c->be->be_acl; i < c->valx;
1141                                         i++ ) {
1142                                         a = *prev;
1143                                         prev = &a->acl_next;
1144                                 }
1145                                 a = *prev;
1146                                 *prev = a->acl_next;
1147                                 acl_free( a );
1148                         }
1149                         break;
1150
1151                 case CFG_OC: {
1152                         CfEntryInfo *ce = c->ca_entry->e_private;
1153                         /* can't modify the hardcoded schema */
1154                         if ( ce->ce_parent->ce_type == Cft_Global )
1155                                 return 1;
1156                         }
1157                         cfn = c->private;
1158                         if ( c->valx < 0 ) {
1159                                 ObjectClass *oc;
1160
1161                                 for( oc = cfn->c_oc_head; oc; oc_next( &oc )) {
1162                                         oc_delete( oc );
1163                                         if ( oc  == cfn->c_oc_tail )
1164                                                 break;
1165                                 }
1166                                 cfn->c_oc_head = cfn->c_oc_tail = NULL;
1167                         } else {
1168                                 ObjectClass *oc, *prev = NULL;
1169
1170                                 for ( i=0, oc=cfn->c_oc_head; i<c->valx; i++) {
1171                                         prev = oc;
1172                                         oc_next( &oc );
1173                                 }
1174                                 oc_delete( oc );
1175                                 if ( cfn->c_oc_tail == oc ) {
1176                                         cfn->c_oc_tail = prev;
1177                                 }
1178                                 if ( cfn->c_oc_head == oc ) {
1179                                         oc_next( &oc );
1180                                         cfn->c_oc_head = oc;
1181                                 }
1182                         }
1183                         break;
1184
1185                 case CFG_ATTR: {
1186                         CfEntryInfo *ce = c->ca_entry->e_private;
1187                         /* can't modify the hardcoded schema */
1188                         if ( ce->ce_parent->ce_type == Cft_Global )
1189                                 return 1;
1190                         }
1191                         cfn = c->private;
1192                         if ( c->valx < 0 ) {
1193                                 AttributeType *at;
1194
1195                                 for( at = cfn->c_at_head; at; at_next( &at )) {
1196                                         at_delete( at );
1197                                         if ( at  == cfn->c_at_tail )
1198                                                 break;
1199                                 }
1200                                 cfn->c_at_head = cfn->c_at_tail = NULL;
1201                         } else {
1202                                 AttributeType *at, *prev = NULL;
1203
1204                                 for ( i=0, at=cfn->c_at_head; i<c->valx; i++) {
1205                                         prev = at;
1206                                         at_next( &at );
1207                                 }
1208                                 at_delete( at );
1209                                 if ( cfn->c_at_tail == at ) {
1210                                         cfn->c_at_tail = prev;
1211                                 }
1212                                 if ( cfn->c_at_head == at ) {
1213                                         at_next( &at );
1214                                         cfn->c_at_head = at;
1215                                 }
1216                         }
1217                         break;
1218
1219                 case CFG_LIMITS:
1220                         /* FIXME: there is no limits_free function */
1221                 case CFG_ATOPT:
1222                         /* FIXME: there is no ad_option_free function */
1223                 case CFG_ROOTDSE:
1224                         /* FIXME: there is no way to remove attributes added by
1225                                 a DSE file */
1226                 case CFG_OID:
1227                 case CFG_DIT:
1228                 case CFG_MODPATH:
1229                 default:
1230                         rc = 1;
1231                         break;
1232                 }
1233                 return rc;
1234         }
1235
1236         switch(c->type) {
1237                 case CFG_BACKEND:
1238                         if(!(c->bi = backend_info(c->argv[1]))) {
1239                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> failed init", c->argv[0] );
1240                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
1241                                         c->log, c->cr_msg, c->argv[1] );
1242                                 return(1);
1243                         }
1244                         break;
1245
1246                 case CFG_DATABASE:
1247                         c->bi = NULL;
1248                         /* NOTE: config is always the first backend!
1249                          */
1250                         if ( !strcasecmp( c->argv[1], "config" )) {
1251                                 c->be = LDAP_STAILQ_FIRST(&backendDB);
1252                         } else if ( !strcasecmp( c->argv[1], "frontend" )) {
1253                                 c->be = frontendDB;
1254                         } else {
1255                                 c->be = backend_db_init(c->argv[1], NULL, c->valx, &c->reply);
1256                                 if ( !c->be ) {
1257                                         if ( c->cr_msg[0] == 0 )
1258                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> failed init", c->argv[0] );
1259                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n", c->log, c->cr_msg, c->argv[1] );
1260                                         return(1);
1261                                 }
1262                         }
1263                         break;
1264
1265                 case CFG_CONCUR:
1266                         ldap_pvt_thread_set_concurrency(c->value_int);
1267                         break;
1268
1269                 case CFG_THREADS:
1270                         if ( c->value_int < 2 ) {
1271                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1272                                         "threads=%d smaller than minimum value 2",
1273                                         c->value_int );
1274                                 Debug(LDAP_DEBUG_ANY, "%s: %s.\n",
1275                                         c->log, c->cr_msg, 0 );
1276                                 return 1;
1277
1278                         } else if ( c->value_int > 2 * SLAP_MAX_WORKER_THREADS ) {
1279                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1280                                         "warning, threads=%d larger than twice the default (2*%d=%d); YMMV",
1281                                         c->value_int, SLAP_MAX_WORKER_THREADS, 2 * SLAP_MAX_WORKER_THREADS );
1282                                 Debug(LDAP_DEBUG_ANY, "%s: %s.\n",
1283                                         c->log, c->cr_msg, 0 );
1284                         }
1285                         if ( slapMode & SLAP_SERVER_MODE )
1286                                 ldap_pvt_thread_pool_maxthreads(&connection_pool, c->value_int);
1287                         connection_pool_max = c->value_int;     /* save for reference */
1288                         break;
1289
1290                 case CFG_TTHREADS:
1291                         if ( slapMode & SLAP_TOOL_MODE )
1292                                 ldap_pvt_thread_pool_maxthreads(&connection_pool, c->value_int);
1293                         slap_tool_thread_max = c->value_int;    /* save for reference */
1294                         break;
1295
1296                 case CFG_SALT:
1297                         if ( passwd_salt ) ch_free( passwd_salt );
1298                         passwd_salt = c->value_string;
1299                         lutil_salt_format(passwd_salt);
1300                         break;
1301
1302                 case CFG_LIMITS:
1303                         if(limits_parse(c->be, c->fname, c->lineno, c->argc, c->argv))
1304                                 return(1);
1305                         break;
1306
1307                 case CFG_RO:
1308                         if(c->value_int)
1309                                 c->be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1310                         else
1311                                 c->be->be_restrictops &= ~SLAP_RESTRICT_OP_WRITES;
1312                         break;
1313
1314                 case CFG_AZPOLICY:
1315                         ch_free(c->value_string);
1316                         if (slap_sasl_setpolicy( c->argv[1] )) {
1317                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1318                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1319                                         c->log, c->cr_msg, c->argv[1] );
1320                                 return(1);
1321                         }
1322                         break;
1323                 
1324                 case CFG_AZREGEXP:
1325                         if (slap_sasl_regexp_config( c->argv[1], c->argv[2] ))
1326                                 return(1);
1327                         break;
1328                                 
1329 #ifdef HAVE_CYRUS_SASL
1330                 case CFG_SASLSECP:
1331                         {
1332                         char *txt = slap_sasl_secprops( c->argv[1] );
1333                         if ( txt ) {
1334                                 snprintf( c->cr_msg, sizeof(c->cr_msg), "<%s> %s",
1335                                         c->argv[0], txt );
1336                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
1337                                 return(1);
1338                         }
1339                         break;
1340                         }
1341 #endif
1342
1343                 case CFG_DEPTH:
1344                         c->be->be_max_deref_depth = c->value_int;
1345                         break;
1346
1347                 case CFG_OID: {
1348                         OidMacro *om;
1349
1350                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1351                                 cfn = c->private;
1352                         if(parse_oidm(c, 1, &om))
1353                                 return(1);
1354                         if (!cfn->c_om_head) cfn->c_om_head = om;
1355                         cfn->c_om_tail = om;
1356                         }
1357                         break;
1358
1359                 case CFG_OC: {
1360                         ObjectClass *oc, *prev;
1361
1362                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1363                                 cfn = c->private;
1364                         if ( c->valx < 0 ) {
1365                                 prev = cfn->c_oc_tail;
1366                         } else {
1367                                 prev = NULL;
1368                                 /* If adding anything after the first, prev is easy */
1369                                 if ( c->valx ) {
1370                                         int i;
1371                                         for (i=0, oc = cfn->c_oc_head; i<c->valx; i++) {
1372                                                 prev = oc;
1373                                                 oc_next( &oc );
1374                                         }
1375                                 } else
1376                                 /* If adding the first, and head exists, find its prev */
1377                                         if (cfn->c_oc_head) {
1378                                         for ( oc_start( &oc ); oc != cfn->c_oc_head; ) {
1379                                                 prev = oc;
1380                                                 oc_next( &oc );
1381                                         }
1382                                 }
1383                                 /* else prev is NULL, append to end of global list */
1384                         }
1385                         if(parse_oc(c, &oc, prev)) return(1);
1386                         if (!cfn->c_oc_head) cfn->c_oc_head = oc;
1387                         if (cfn->c_oc_tail == prev) cfn->c_oc_tail = oc;
1388                         }
1389                         break;
1390
1391                 case CFG_ATTR: {
1392                         AttributeType *at, *prev;
1393
1394                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1395                                 cfn = c->private;
1396                         if ( c->valx < 0 ) {
1397                                 prev = cfn->c_at_tail;
1398                         } else {
1399                                 prev = NULL;
1400                                 /* If adding anything after the first, prev is easy */
1401                                 if ( c->valx ) {
1402                                         int i;
1403                                         for (i=0, at = cfn->c_at_head; i<c->valx; i++) {
1404                                                 prev = at;
1405                                                 at_next( &at );
1406                                         }
1407                                 } else
1408                                 /* If adding the first, and head exists, find its prev */
1409                                         if (cfn->c_at_head) {
1410                                         for ( at_start( &at ); at != cfn->c_at_head; ) {
1411                                                 prev = at;
1412                                                 at_next( &at );
1413                                         }
1414                                 }
1415                                 /* else prev is NULL, append to end of global list */
1416                         }
1417                         if(parse_at(c, &at, prev)) return(1);
1418                         if (!cfn->c_at_head) cfn->c_at_head = at;
1419                         if (cfn->c_at_tail == prev) cfn->c_at_tail = at;
1420                         }
1421                         break;
1422
1423                 case CFG_DIT: {
1424                         ContentRule *cr;
1425
1426                         if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1427                                 cfn = c->private;
1428                         if(parse_cr(c, &cr)) return(1);
1429                         if (!cfn->c_cr_head) cfn->c_cr_head = cr;
1430                         cfn->c_cr_tail = cr;
1431                         }
1432                         break;
1433
1434                 case CFG_ATOPT:
1435                         ad_define_option(NULL, NULL, 0);
1436                         for(i = 1; i < c->argc; i++)
1437                                 if(ad_define_option(c->argv[i], c->fname, c->lineno))
1438                                         return(1);
1439                         break;
1440
1441                 case CFG_ACL:
1442                         /* Don't append to the global ACL if we're on a specific DB */
1443                         i = c->valx;
1444                         if ( c->be != frontendDB && frontendDB->be_acl && c->valx == -1 ) {
1445                                 AccessControl *a;
1446                                 i = 0;
1447                                 for ( a=c->be->be_acl; a && a != frontendDB->be_acl;
1448                                         a = a->acl_next )
1449                                         i++;
1450                         }
1451                         if ( parse_acl(c->be, c->fname, c->lineno, c->argc, c->argv, i ) ) {
1452                                 return 1;
1453                         }
1454                         break;
1455
1456                 case CFG_ROOTDSE:
1457                         if(root_dse_read_file(c->argv[1])) {
1458                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> could not read file", c->argv[0] );
1459                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1460                                         c->log, c->cr_msg, c->argv[1] );
1461                                 return(1);
1462                         }
1463                         {
1464                                 struct berval bv;
1465                                 ber_str2bv( c->argv[1], 0, 1, &bv );
1466                                 if ( c->op == LDAP_MOD_ADD && c->private && cfn != c->private )
1467                                         cfn = c->private;
1468                                 ber_bvarray_add( &cfn->c_dseFiles, &bv );
1469                         }
1470                         break;
1471
1472                 case CFG_SERVERID:
1473                         {
1474                                 ServerID *si, **sip;
1475                                 LDAPURLDesc *lud;
1476                                 int num;
1477                                 if ( lutil_atoi( &num, c->argv[1] ) ||
1478                                         num < 0 || num > SLAP_SYNC_SID_MAX )
1479                                 {
1480                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
1481                                                 "<%s> illegal server ID", c->argv[0] );
1482                                         Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1483                                                 c->log, c->cr_msg, c->argv[1] );
1484                                         return 1;
1485                                 }
1486                                 /* only one value allowed if no URL is given */
1487                                 if ( c->argc > 2 ) {
1488                                         int len;
1489
1490                                         if ( sid_list && BER_BVISEMPTY( &sid_list->si_url )) {
1491                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1492                                                         "<%s> only one server ID allowed now", c->argv[0] );
1493                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1494                                                         c->log, c->cr_msg, c->argv[1] );
1495                                                 return 1;
1496                                         }
1497
1498                                         if ( ldap_url_parse( c->argv[2], &lud )) {
1499                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1500                                                         "<%s> invalid URL", c->argv[0] );
1501                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1502                                                         c->log, c->cr_msg, c->argv[2] );
1503                                                 return 1;
1504                                         }
1505                                         len = strlen( c->argv[2] );
1506                                         si = ch_malloc( sizeof(ServerID) + len + 1 );
1507                                         si->si_url.bv_val = (char *)(si+1);
1508                                         si->si_url.bv_len = len;
1509                                         strcpy( si->si_url.bv_val, c->argv[2] );
1510                                 } else {
1511                                         if ( sid_list ) {
1512                                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
1513                                                         "<%s> unqualified server ID not allowed now", c->argv[0] );
1514                                                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
1515                                                         c->log, c->cr_msg, c->argv[1] );
1516                                                 return 1;
1517                                         }
1518                                         si = ch_malloc( sizeof(ServerID) );
1519                                         BER_BVZERO( &si->si_url );
1520                                         slap_serverID = num;
1521                                         Debug( LDAP_DEBUG_CONFIG,
1522                                                 "%s: SID=%d\n",
1523                                                 c->log, slap_serverID, 0 );
1524                                 }
1525                                 si->si_next = NULL;
1526                                 si->si_num = num;
1527                                 for ( sip = &sid_list; *sip; sip = &(*sip)->si_next );
1528                                 *sip = si;
1529
1530                                 if (( slapMode & SLAP_SERVER_MODE ) && c->argc > 2 ) {
1531                                         /* If hostname is empty, or is localhost, or matches
1532                                          * our hostname, this serverID refers to this host.
1533                                          * Compare it against listeners and ports.
1534                                          */
1535                                         if ( !lud->lud_host || !lud->lud_host[0] ||
1536                                                 !strncasecmp("localhost", lud->lud_host,
1537                                                         STRLENOF("localhost")) ||
1538                                                 !strcasecmp( global_host, lud->lud_host )) {
1539                                                 Listener **l = slapd_get_listeners();
1540                                                 int i;
1541
1542                                                 for ( i=0; l[i]; i++ ) {
1543                                                         LDAPURLDesc *lu2;
1544                                                         int isMe = 0;
1545                                                         ldap_url_parse( l[i]->sl_url.bv_val, &lu2 );
1546                                                         do {
1547                                                                 if ( strcasecmp( lud->lud_scheme,
1548                                                                         lu2->lud_scheme ))
1549                                                                         break;
1550                                                                 if ( lud->lud_port != lu2->lud_port )
1551                                                                         break;
1552                                                                 /* Listener on ANY address */
1553                                                                 if ( !lu2->lud_host || !lu2->lud_host[0] ) {
1554                                                                         isMe = 1;
1555                                                                         break;
1556                                                                 }
1557                                                                 /* URL on ANY address */
1558                                                                 if ( !lud->lud_host || !lud->lud_host[0] ) {
1559                                                                         isMe = 1;
1560                                                                         break;
1561                                                                 }
1562                                                                 /* Listener has specific host, must
1563                                                                  * match it
1564                                                                  */
1565                                                                 if ( !strcasecmp( lud->lud_host,
1566                                                                         lu2->lud_host )) {
1567                                                                         isMe = 1;
1568                                                                         break;
1569                                                                 }
1570                                                         } while(0);
1571                                                         ldap_free_urldesc( lu2 );
1572                                                         if ( isMe ) {
1573                                                                 slap_serverID = si->si_num;
1574                                                                 Debug( LDAP_DEBUG_CONFIG,
1575                                                                         "%s: SID=%d (listener=%s)\n",
1576                                                                         c->log, slap_serverID,
1577                                                                         l[i]->sl_url.bv_val );
1578                                                                 break;
1579                                                         }
1580                                                 }
1581                                         }
1582                                 }
1583                                 if ( c->argc > 2 )
1584                                         ldap_free_urldesc( lud );
1585                         }
1586                         break;
1587                 case CFG_LOGFILE: {
1588                                 FILE *logfile;
1589                                 if ( logfileName ) ch_free( logfileName );
1590                                 logfileName = c->value_string;
1591                                 logfile = fopen(logfileName, "w");
1592                                 if(logfile) lutil_debug_file(logfile);
1593                         } break;
1594
1595                 case CFG_LASTMOD:
1596                         if(SLAP_NOLASTMODCMD(c->be)) {
1597                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> not available for %s database",
1598                                         c->argv[0], c->be->bd_info->bi_type );
1599                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1600                                         c->log, c->cr_msg, 0 );
1601                                 return(1);
1602                         }
1603                         if(c->value_int)
1604                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_NOLASTMOD;
1605                         else
1606                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NOLASTMOD;
1607                         break;
1608
1609                 case CFG_MIRRORMODE:
1610                         if(!SLAP_SHADOW(c->be)) {
1611                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database is not a shadow",
1612                                         c->argv[0] );
1613                                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1614                                         c->log, c->cr_msg, 0 );
1615                                 return(1);
1616                         }
1617                         if(c->value_int)
1618                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_SINGLE_SHADOW;
1619                         else
1620                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_SINGLE_SHADOW;
1621                         break;
1622
1623                 case CFG_MONITORING:
1624                         if(c->value_int)
1625                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_MONITORING;
1626                         else
1627                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_MONITORING;
1628                         break;
1629
1630                 case CFG_HIDDEN:
1631                         if (c->value_int)
1632                                 SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_HIDDEN;
1633                         else
1634                                 SLAP_DBFLAGS(c->be) &= ~SLAP_DBFLAG_HIDDEN;
1635                         break;
1636
1637                 case CFG_SSTR_IF_MAX:
1638                         if (c->value_int < index_substr_if_minlen) {
1639                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1640                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1641                                         c->log, c->cr_msg, c->value_int );
1642                                 return(1);
1643                         }
1644                         index_substr_if_maxlen = c->value_int;
1645                         break;
1646
1647                 case CFG_SSTR_IF_MIN:
1648                         if (c->value_int > index_substr_if_maxlen) {
1649                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value", c->argv[0] );
1650                                 Debug(LDAP_DEBUG_ANY, "%s: %s (%d)\n",
1651                                         c->log, c->cr_msg, c->value_int );
1652                                 return(1);
1653                         }
1654                         index_substr_if_minlen = c->value_int;
1655                         break;
1656
1657 #ifdef SLAPD_MODULES
1658                 case CFG_MODLOAD:
1659                         /* If we're just adding a module on an existing modpath,
1660                          * make sure we've selected the current path.
1661                          */
1662                         if ( c->op == LDAP_MOD_ADD && c->private && modcur != c->private ) {
1663                                 modcur = c->private;
1664                                 /* This should never fail */
1665                                 if ( module_path( modcur->mp_path.bv_val )) {
1666                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> module path no longer valid",
1667                                                 c->argv[0] );
1668                                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1669                                                 c->log, c->cr_msg, modcur->mp_path.bv_val );
1670                                         return(1);
1671                                 }
1672                         }
1673                         if(module_load(c->argv[1], c->argc - 2, (c->argc > 2) ? c->argv + 2 : NULL))
1674                                 return(1);
1675                         /* Record this load on the current path */
1676                         {
1677                                 struct berval bv;
1678                                 char *ptr;
1679                                 if ( c->op == SLAP_CONFIG_ADD ) {
1680                                         ptr = c->line + STRLENOF("moduleload");
1681                                         while (!isspace((unsigned char) *ptr)) ptr++;
1682                                         while (isspace((unsigned char) *ptr)) ptr++;
1683                                 } else {
1684                                         ptr = c->line;
1685                                 }
1686                                 ber_str2bv(ptr, 0, 1, &bv);
1687                                 ber_bvarray_add( &modcur->mp_loads, &bv );
1688                         }
1689                         /* Check for any new hardcoded schema */
1690                         if ( c->op == LDAP_MOD_ADD && CONFIG_ONLINE_ADD( c )) {
1691                                 config_check_schema( NULL, &cfBackInfo );
1692                         }
1693                         break;
1694
1695                 case CFG_MODPATH:
1696                         if(module_path(c->argv[1])) return(1);
1697                         /* Record which path was used with each module */
1698                         {
1699                                 ModPaths *mp;
1700
1701                                 if (!modpaths.mp_loads) {
1702                                         mp = &modpaths;
1703                                 } else {
1704                                         mp = ch_malloc( sizeof( ModPaths ));
1705                                         modlast->mp_next = mp;
1706                                 }
1707                                 ber_str2bv(c->argv[1], 0, 1, &mp->mp_path);
1708                                 mp->mp_next = NULL;
1709                                 mp->mp_loads = NULL;
1710                                 modlast = mp;
1711                                 c->private = mp;
1712                                 modcur = mp;
1713                         }
1714                         
1715                         break;
1716 #endif
1717
1718 #ifdef LDAP_SLAPI
1719                 case CFG_PLUGIN:
1720                         if(slapi_int_read_config(c->be, c->fname, c->lineno, c->argc, c->argv) != LDAP_SUCCESS)
1721                                 return(1);
1722                         slapi_plugins_used++;
1723                         break;
1724 #endif
1725
1726 #ifdef SLAP_AUTH_REWRITE
1727                 case CFG_REWRITE: {
1728                         struct berval bv;
1729                         char *line;
1730                         
1731                         if(slap_sasl_rewrite_config(c->fname, c->lineno, c->argc, c->argv))
1732                                 return(1);
1733
1734                         if ( c->argc > 1 ) {
1735                                 char    *s;
1736
1737                                 /* quote all args but the first */
1738                                 line = ldap_charray2str( c->argv, "\" \"" );
1739                                 ber_str2bv( line, 0, 0, &bv );
1740                                 s = ber_bvchr( &bv, '"' );
1741                                 assert( s != NULL );
1742                                 /* move the trailing quote of argv[0] to the end */
1743                                 AC_MEMCPY( s, s + 1, bv.bv_len - ( s - bv.bv_val ) );
1744                                 bv.bv_val[ bv.bv_len - 1 ] = '"';
1745
1746                         } else {
1747                                 ber_str2bv( c->argv[ 0 ], 0, 1, &bv );
1748                         }
1749                         
1750                         ber_bvarray_add( &authz_rewrites, &bv );
1751                         }
1752                         break;
1753 #endif
1754
1755
1756                 default:
1757                         Debug( LDAP_DEBUG_ANY,
1758                                 "%s: unknown CFG_TYPE %d.\n",
1759                                 c->log, c->type, 0 );
1760                         return 1;
1761
1762         }
1763         return(0);
1764 }
1765
1766
1767 static int
1768 config_fname(ConfigArgs *c) {
1769         if(c->op == SLAP_CONFIG_EMIT) {
1770                 if (c->private) {
1771                         ConfigFile *cf = c->private;
1772                         value_add_one( &c->rvalue_vals, &cf->c_file );
1773                         return 0;
1774                 }
1775                 return 1;
1776         }
1777         return(0);
1778 }
1779
1780 static int
1781 config_cfdir(ConfigArgs *c) {
1782         if(c->op == SLAP_CONFIG_EMIT) {
1783                 if ( !BER_BVISEMPTY( &cfdir )) {
1784                         value_add_one( &c->rvalue_vals, &cfdir );
1785                         return 0;
1786                 }
1787                 return 1;
1788         }
1789         return(0);
1790 }
1791
1792 static int
1793 config_search_base(ConfigArgs *c) {
1794         if(c->op == SLAP_CONFIG_EMIT) {
1795                 int rc = 1;
1796                 if (!BER_BVISEMPTY(&default_search_base)) {
1797                         value_add_one(&c->rvalue_vals, &default_search_base);
1798                         value_add_one(&c->rvalue_nvals, &default_search_nbase);
1799                         rc = 0;
1800                 }
1801                 return rc;
1802         } else if( c->op == LDAP_MOD_DELETE ) {
1803                 ch_free( default_search_base.bv_val );
1804                 ch_free( default_search_nbase.bv_val );
1805                 BER_BVZERO( &default_search_base );
1806                 BER_BVZERO( &default_search_nbase );
1807                 return 0;
1808         }
1809
1810         if(c->bi || c->be != frontendDB) {
1811                 Debug(LDAP_DEBUG_ANY, "%s: defaultSearchBase line must appear "
1812                         "prior to any backend or database definition\n",
1813                         c->log, 0, 0);
1814                 return(1);
1815         }
1816
1817         if(default_search_nbase.bv_len) {
1818                 free(default_search_base.bv_val);
1819                 free(default_search_nbase.bv_val);
1820         }
1821
1822         default_search_base = c->value_dn;
1823         default_search_nbase = c->value_ndn;
1824         return(0);
1825 }
1826
1827 static int
1828 config_passwd_hash(ConfigArgs *c) {
1829         int i;
1830         if (c->op == SLAP_CONFIG_EMIT) {
1831                 struct berval bv;
1832                 for (i=0; default_passwd_hash && default_passwd_hash[i]; i++) {
1833                         ber_str2bv(default_passwd_hash[i], 0, 0, &bv);
1834                         value_add_one(&c->rvalue_vals, &bv);
1835                 }
1836                 return i ? 0 : 1;
1837         } else if ( c->op == LDAP_MOD_DELETE ) {
1838                 if ( c->valx < 0 ) {
1839                         ldap_charray_free( default_passwd_hash );
1840                         default_passwd_hash = NULL;
1841                 } else {
1842                         i = c->valx;
1843                         ch_free( default_passwd_hash[i] );
1844                         for (; default_passwd_hash[i]; i++ )
1845                                 default_passwd_hash[i] = default_passwd_hash[i+1];
1846                 }
1847                 return 0;
1848         }
1849         if(default_passwd_hash) {
1850                 Debug(LDAP_DEBUG_ANY, "%s: "
1851                         "already set default password_hash\n",
1852                         c->log, 0, 0);
1853                 return(1);
1854         }
1855         for(i = 1; i < c->argc; i++) {
1856                 if(!lutil_passwd_scheme(c->argv[i])) {
1857                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> scheme not available", c->argv[0] );
1858                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
1859                                 c->log, c->cr_msg, c->argv[i]);
1860                 } else {
1861                         ldap_charray_add(&default_passwd_hash, c->argv[i]);
1862                 }
1863                 if(!default_passwd_hash) {
1864                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> no valid hashes found", c->argv[0] );
1865                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
1866                                 c->log, c->cr_msg, 0 );
1867                         return(1);
1868                 }
1869         }
1870         return(0);
1871 }
1872
1873 static int
1874 config_schema_dn(ConfigArgs *c) {
1875         if ( c->op == SLAP_CONFIG_EMIT ) {
1876                 int rc = 1;
1877                 if ( !BER_BVISEMPTY( &c->be->be_schemadn )) {
1878                         value_add_one(&c->rvalue_vals, &c->be->be_schemadn);
1879                         value_add_one(&c->rvalue_nvals, &c->be->be_schemandn);
1880                         rc = 0;
1881                 }
1882                 return rc;
1883         } else if ( c->op == LDAP_MOD_DELETE ) {
1884                 ch_free( c->be->be_schemadn.bv_val );
1885                 ch_free( c->be->be_schemandn.bv_val );
1886                 BER_BVZERO( &c->be->be_schemadn );
1887                 BER_BVZERO( &c->be->be_schemandn );
1888                 return 0;
1889         }
1890         ch_free( c->be->be_schemadn.bv_val );
1891         ch_free( c->be->be_schemandn.bv_val );
1892         c->be->be_schemadn = c->value_dn;
1893         c->be->be_schemandn = c->value_ndn;
1894         return(0);
1895 }
1896
1897 static int
1898 config_sizelimit(ConfigArgs *c) {
1899         int i, rc = 0;
1900         struct slap_limits_set *lim = &c->be->be_def_limit;
1901         if (c->op == SLAP_CONFIG_EMIT) {
1902                 char buf[8192];
1903                 struct berval bv;
1904                 bv.bv_val = buf;
1905                 bv.bv_len = 0;
1906                 limits_unparse_one( lim, SLAP_LIMIT_SIZE, &bv, sizeof( buf ) );
1907                 if ( !BER_BVISEMPTY( &bv ))
1908                         value_add_one( &c->rvalue_vals, &bv );
1909                 else
1910                         rc = 1;
1911                 return rc;
1912         } else if ( c->op == LDAP_MOD_DELETE ) {
1913                 /* Reset to defaults */
1914                 lim->lms_s_soft = SLAPD_DEFAULT_SIZELIMIT;
1915                 lim->lms_s_hard = 0;
1916                 lim->lms_s_unchecked = -1;
1917                 lim->lms_s_pr = 0;
1918                 lim->lms_s_pr_hide = 0;
1919                 lim->lms_s_pr_total = 0;
1920                 return 0;
1921         }
1922         for(i = 1; i < c->argc; i++) {
1923                 if(!strncasecmp(c->argv[i], "size", 4)) {
1924                         rc = limits_parse_one(c->argv[i], lim);
1925                         if ( rc ) {
1926                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1927                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1928                                         c->log, c->cr_msg, c->argv[i]);
1929                                 return(1);
1930                         }
1931                 } else {
1932                         if(!strcasecmp(c->argv[i], "unlimited")) {
1933                                 lim->lms_s_soft = -1;
1934                         } else {
1935                                 if ( lutil_atoix( &lim->lms_s_soft, c->argv[i], 0 ) != 0 ) {
1936                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1937                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1938                                                 c->log, c->cr_msg, c->argv[i]);
1939                                         return(1);
1940                                 }
1941                         }
1942                         lim->lms_s_hard = 0;
1943                 }
1944         }
1945         return(0);
1946 }
1947
1948 static int
1949 config_timelimit(ConfigArgs *c) {
1950         int i, rc = 0;
1951         struct slap_limits_set *lim = &c->be->be_def_limit;
1952         if (c->op == SLAP_CONFIG_EMIT) {
1953                 char buf[8192];
1954                 struct berval bv;
1955                 bv.bv_val = buf;
1956                 bv.bv_len = 0;
1957                 limits_unparse_one( lim, SLAP_LIMIT_TIME, &bv, sizeof( buf ) );
1958                 if ( !BER_BVISEMPTY( &bv ))
1959                         value_add_one( &c->rvalue_vals, &bv );
1960                 else
1961                         rc = 1;
1962                 return rc;
1963         } else if ( c->op == LDAP_MOD_DELETE ) {
1964                 /* Reset to defaults */
1965                 lim->lms_t_soft = SLAPD_DEFAULT_TIMELIMIT;
1966                 lim->lms_t_hard = 0;
1967                 return 0;
1968         }
1969         for(i = 1; i < c->argc; i++) {
1970                 if(!strncasecmp(c->argv[i], "time", 4)) {
1971                         rc = limits_parse_one(c->argv[i], lim);
1972                         if ( rc ) {
1973                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse value", c->argv[0] );
1974                                 Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1975                                         c->log, c->cr_msg, c->argv[i]);
1976                                 return(1);
1977                         }
1978                 } else {
1979                         if(!strcasecmp(c->argv[i], "unlimited")) {
1980                                 lim->lms_t_soft = -1;
1981                         } else {
1982                                 if ( lutil_atoix( &lim->lms_t_soft, c->argv[i], 0 ) != 0 ) {
1983                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse limit", c->argv[0]);
1984                                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
1985                                                 c->log, c->cr_msg, c->argv[i]);
1986                                         return(1);
1987                                 }
1988                         }
1989                         lim->lms_t_hard = 0;
1990                 }
1991         }
1992         return(0);
1993 }
1994
1995 static int
1996 config_overlay(ConfigArgs *c) {
1997         if (c->op == SLAP_CONFIG_EMIT) {
1998                 return 1;
1999         } else if ( c->op == LDAP_MOD_DELETE ) {
2000                 assert(0);
2001         }
2002         if(c->argv[1][0] == '-' && overlay_config(c->be, &c->argv[1][1],
2003                 c->valx, &c->bi)) {
2004                 /* log error */
2005                 Debug( LDAP_DEBUG_ANY,
2006                         "%s: (optional) %s overlay \"%s\" configuration failed.\n",
2007                         c->log, c->be == frontendDB ? "global " : "", &c->argv[1][1]);
2008                 return 1;
2009         } else if(overlay_config(c->be, c->argv[1], c->valx, &c->bi)) {
2010                 return(1);
2011         }
2012         return(0);
2013 }
2014
2015 static int
2016 config_subordinate(ConfigArgs *c)
2017 {
2018         int rc = 1;
2019         int advertise;
2020
2021         switch( c->op ) {
2022         case SLAP_CONFIG_EMIT:
2023                 if ( SLAP_GLUE_SUBORDINATE( c->be )) {
2024                         struct berval bv;
2025
2026                         bv.bv_val = SLAP_GLUE_ADVERTISE( c->be ) ? "advertise" : "TRUE";
2027                         bv.bv_len = SLAP_GLUE_ADVERTISE( c->be ) ? STRLENOF("advertise") :
2028                                 STRLENOF("TRUE");
2029
2030                         value_add_one( &c->rvalue_vals, &bv );
2031                         rc = 0;
2032                 }
2033                 break;
2034         case LDAP_MOD_DELETE:
2035                 if ( !c->line  || strcasecmp( c->line, "advertise" )) {
2036                         glue_sub_del( c->be );
2037                 } else {
2038                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_GLUE_ADVERTISE;
2039                 }
2040                 rc = 0;
2041                 break;
2042         case LDAP_MOD_ADD:
2043         case SLAP_CONFIG_ADD:
2044                 advertise = ( c->argc == 2 && !strcasecmp( c->argv[1], "advertise" ));
2045                 rc = glue_sub_add( c->be, advertise, CONFIG_ONLINE_ADD( c ));
2046                 break;
2047         }
2048         return rc;
2049 }
2050
2051 static int
2052 config_suffix(ConfigArgs *c)
2053 {
2054         Backend *tbe;
2055         struct berval pdn, ndn;
2056         char    *notallowed = NULL;
2057
2058         if ( c->be == frontendDB ) {
2059                 notallowed = "frontend";
2060
2061         } else if ( SLAP_MONITOR(c->be) ) {
2062                 notallowed = "monitor";
2063
2064         } else if ( SLAP_CONFIG(c->be) ) {
2065                 notallowed = "config";
2066         }
2067
2068         if ( notallowed != NULL ) {
2069                 char    buf[ SLAP_TEXT_BUFLEN ] = { '\0' };
2070
2071                 switch ( c->op ) {
2072                 case LDAP_MOD_ADD:
2073                 case LDAP_MOD_DELETE:
2074                 case LDAP_MOD_REPLACE:
2075                 case LDAP_MOD_INCREMENT:
2076                 case SLAP_CONFIG_ADD:
2077                         if ( !BER_BVISNULL( &c->value_dn ) ) {
2078                                 snprintf( buf, sizeof( buf ), "<%s> ",
2079                                                 c->value_dn.bv_val );
2080                         }
2081
2082                         Debug(LDAP_DEBUG_ANY,
2083                                 "%s: suffix %snot allowed in %s database.\n",
2084                                 c->log, buf, notallowed );
2085                         break;
2086
2087                 case SLAP_CONFIG_EMIT:
2088                         /* don't complain when emitting... */
2089                         break;
2090
2091                 default:
2092                         /* FIXME: don't know what values may be valid;
2093                          * please remove assertion, or add legal values
2094                          * to either block */
2095                         assert( 0 );
2096                         break;
2097                 }
2098
2099                 return 1;
2100         }
2101
2102         if (c->op == SLAP_CONFIG_EMIT) {
2103                 if ( c->be->be_suffix == NULL
2104                                 || BER_BVISNULL( &c->be->be_suffix[0] ) )
2105                 {
2106                         return 1;
2107                 } else {
2108                         value_add( &c->rvalue_vals, c->be->be_suffix );
2109                         value_add( &c->rvalue_nvals, c->be->be_nsuffix );
2110                         return 0;
2111                 }
2112         } else if ( c->op == LDAP_MOD_DELETE ) {
2113                 if ( c->valx < 0 ) {
2114                         ber_bvarray_free( c->be->be_suffix );
2115                         ber_bvarray_free( c->be->be_nsuffix );
2116                         c->be->be_suffix = NULL;
2117                         c->be->be_nsuffix = NULL;
2118                 } else {
2119                         int i = c->valx;
2120                         ch_free( c->be->be_suffix[i].bv_val );
2121                         ch_free( c->be->be_nsuffix[i].bv_val );
2122                         do {
2123                                 c->be->be_suffix[i] = c->be->be_suffix[i+1];
2124                                 c->be->be_nsuffix[i] = c->be->be_nsuffix[i+1];
2125                                 i++;
2126                         } while ( !BER_BVISNULL( &c->be->be_suffix[i] ) );
2127                 }
2128                 return 0;
2129         }
2130
2131 #ifdef SLAPD_MONITOR_DN
2132         if(!strcasecmp(c->argv[1], SLAPD_MONITOR_DN)) {
2133                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> DN is reserved for monitoring slapd",
2134                         c->argv[0] );
2135                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2136                         c->log, c->cr_msg, SLAPD_MONITOR_DN);
2137                 return(1);
2138         }
2139 #endif
2140
2141         pdn = c->value_dn;
2142         ndn = c->value_ndn;
2143         if (SLAP_DBHIDDEN( c->be ))
2144                 tbe = NULL;
2145         else
2146                 tbe = select_backend(&ndn, 0);
2147         if(tbe == c->be) {
2148                 Debug( LDAP_DEBUG_ANY, "%s: suffix already served by this backend!.\n",
2149                         c->log, 0, 0);
2150                 return 1;
2151                 free(pdn.bv_val);
2152                 free(ndn.bv_val);
2153         } else if(tbe) {
2154                 BackendDB *b2 = tbe;
2155
2156                 /* Does tbe precede be? */
2157                 while (( b2 = LDAP_STAILQ_NEXT(b2, be_next )) && b2 && b2 != c->be );
2158
2159                 if ( b2 ) {
2160                         char    *type = tbe->bd_info->bi_type;
2161
2162                         if ( overlay_is_over( tbe ) ) {
2163                                 slap_overinfo   *oi = (slap_overinfo *)tbe->bd_info->bi_private;
2164                                 type = oi->oi_orig->bi_type;
2165                         }
2166
2167                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> namingContext \"%s\" "
2168                                 "already served by a preceding %s database",
2169                                 c->argv[0], pdn.bv_val, type );
2170                         Debug(LDAP_DEBUG_ANY, "%s: %s serving namingContext \"%s\"\n",
2171                                 c->log, c->cr_msg, tbe->be_suffix[0].bv_val);
2172                         free(pdn.bv_val);
2173                         free(ndn.bv_val);
2174                         return(1);
2175                 }
2176         }
2177         if(pdn.bv_len == 0 && default_search_nbase.bv_len) {
2178                 Debug(LDAP_DEBUG_ANY, "%s: suffix DN empty and default search "
2179                         "base provided \"%s\" (assuming okay)\n",
2180                         c->log, default_search_base.bv_val, 0);
2181         }
2182         ber_bvarray_add(&c->be->be_suffix, &pdn);
2183         ber_bvarray_add(&c->be->be_nsuffix, &ndn);
2184         return(0);
2185 }
2186
2187 static int
2188 config_rootdn(ConfigArgs *c) {
2189         if (c->op == SLAP_CONFIG_EMIT) {
2190                 if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2191                         value_add_one(&c->rvalue_vals, &c->be->be_rootdn);
2192                         value_add_one(&c->rvalue_nvals, &c->be->be_rootndn);
2193                         return 0;
2194                 } else {
2195                         return 1;
2196                 }
2197         } else if ( c->op == LDAP_MOD_DELETE ) {
2198                 ch_free( c->be->be_rootdn.bv_val );
2199                 ch_free( c->be->be_rootndn.bv_val );
2200                 BER_BVZERO( &c->be->be_rootdn );
2201                 BER_BVZERO( &c->be->be_rootndn );
2202                 return 0;
2203         }
2204         if ( !BER_BVISNULL( &c->be->be_rootdn )) {
2205                 ch_free( c->be->be_rootdn.bv_val );
2206                 ch_free( c->be->be_rootndn.bv_val );
2207         }
2208         c->be->be_rootdn = c->value_dn;
2209         c->be->be_rootndn = c->value_ndn;
2210         return(0);
2211 }
2212
2213 static int
2214 config_rootpw(ConfigArgs *c) {
2215         Backend *tbe;
2216
2217         if (c->op == SLAP_CONFIG_EMIT) {
2218                 if (!BER_BVISEMPTY(&c->be->be_rootpw)) {
2219                         /* don't copy, because "rootpw" is marked
2220                          * as CFG_BERVAL */
2221                         c->value_bv = c->be->be_rootpw;
2222                         return 0;
2223                 }
2224                 return 1;
2225         } else if ( c->op == LDAP_MOD_DELETE ) {
2226                 ch_free( c->be->be_rootpw.bv_val );
2227                 BER_BVZERO( &c->be->be_rootpw );
2228                 return 0;
2229         }
2230
2231         tbe = select_backend(&c->be->be_rootndn, 0);
2232         if(tbe != c->be) {
2233                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> can only be set when rootdn is under suffix",
2234                         c->argv[0] );
2235                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2236                         c->log, c->cr_msg, 0);
2237                 return(1);
2238         }
2239         if ( !BER_BVISNULL( &c->be->be_rootpw ))
2240                 ch_free( c->be->be_rootpw.bv_val );
2241         c->be->be_rootpw = c->value_bv;
2242         return(0);
2243 }
2244
2245 static int
2246 config_restrict(ConfigArgs *c) {
2247         slap_mask_t restrictops = 0;
2248         int i;
2249         slap_verbmasks restrictable_ops[] = {
2250                 { BER_BVC("bind"),              SLAP_RESTRICT_OP_BIND },
2251                 { BER_BVC("add"),               SLAP_RESTRICT_OP_ADD },
2252                 { BER_BVC("modify"),            SLAP_RESTRICT_OP_MODIFY },
2253                 { BER_BVC("rename"),            SLAP_RESTRICT_OP_RENAME },
2254                 { BER_BVC("modrdn"),            0 },
2255                 { BER_BVC("delete"),            SLAP_RESTRICT_OP_DELETE },
2256                 { BER_BVC("search"),            SLAP_RESTRICT_OP_SEARCH },
2257                 { BER_BVC("compare"),           SLAP_RESTRICT_OP_COMPARE },
2258                 { BER_BVC("read"),              SLAP_RESTRICT_OP_READS },
2259                 { BER_BVC("write"),             SLAP_RESTRICT_OP_WRITES },
2260                 { BER_BVC("extended"),          SLAP_RESTRICT_OP_EXTENDED },
2261                 { BER_BVC("extended=" LDAP_EXOP_START_TLS ),            SLAP_RESTRICT_EXOP_START_TLS },
2262                 { BER_BVC("extended=" LDAP_EXOP_MODIFY_PASSWD ),        SLAP_RESTRICT_EXOP_MODIFY_PASSWD },
2263                 { BER_BVC("extended=" LDAP_EXOP_X_WHO_AM_I ),           SLAP_RESTRICT_EXOP_WHOAMI },
2264                 { BER_BVC("extended=" LDAP_EXOP_X_CANCEL ),             SLAP_RESTRICT_EXOP_CANCEL },
2265                 { BER_BVC("all"),               SLAP_RESTRICT_OP_ALL },
2266                 { BER_BVNULL,   0 }
2267         };
2268
2269         if (c->op == SLAP_CONFIG_EMIT) {
2270                 return mask_to_verbs( restrictable_ops, c->be->be_restrictops,
2271                         &c->rvalue_vals );
2272         } else if ( c->op == LDAP_MOD_DELETE ) {
2273                 if ( !c->line ) {
2274                         c->be->be_restrictops = 0;
2275                 } else {
2276                         restrictops = verb_to_mask( c->line, restrictable_ops );
2277                         c->be->be_restrictops ^= restrictops;
2278                 }
2279                 return 0;
2280         }
2281         i = verbs_to_mask( c->argc, c->argv, restrictable_ops, &restrictops );
2282         if ( i ) {
2283                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown operation", c->argv[0] );
2284                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2285                         c->log, c->cr_msg, c->argv[i]);
2286                 return(1);
2287         }
2288         if ( restrictops & SLAP_RESTRICT_OP_EXTENDED )
2289                 restrictops &= ~SLAP_RESTRICT_EXOP_MASK;
2290         c->be->be_restrictops |= restrictops;
2291         return(0);
2292 }
2293
2294 static int
2295 config_allows(ConfigArgs *c) {
2296         slap_mask_t allows = 0;
2297         int i;
2298         slap_verbmasks allowable_ops[] = {
2299                 { BER_BVC("bind_v2"),           SLAP_ALLOW_BIND_V2 },
2300                 { BER_BVC("bind_anon_cred"),    SLAP_ALLOW_BIND_ANON_CRED },
2301                 { BER_BVC("bind_anon_dn"),      SLAP_ALLOW_BIND_ANON_DN },
2302                 { BER_BVC("update_anon"),       SLAP_ALLOW_UPDATE_ANON },
2303                 { BER_BVC("proxy_authz_anon"),  SLAP_ALLOW_PROXY_AUTHZ_ANON },
2304                 { BER_BVNULL,   0 }
2305         };
2306         if (c->op == SLAP_CONFIG_EMIT) {
2307                 return mask_to_verbs( allowable_ops, global_allows, &c->rvalue_vals );
2308         } else if ( c->op == LDAP_MOD_DELETE ) {
2309                 if ( !c->line ) {
2310                         global_allows = 0;
2311                 } else {
2312                         allows = verb_to_mask( c->line, allowable_ops );
2313                         global_allows ^= allows;
2314                 }
2315                 return 0;
2316         }
2317         i = verbs_to_mask(c->argc, c->argv, allowable_ops, &allows);
2318         if ( i ) {
2319                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2320                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2321                         c->log, c->cr_msg, c->argv[i]);
2322                 return(1);
2323         }
2324         global_allows |= allows;
2325         return(0);
2326 }
2327
2328 static int
2329 config_disallows(ConfigArgs *c) {
2330         slap_mask_t disallows = 0;
2331         int i;
2332         slap_verbmasks disallowable_ops[] = {
2333                 { BER_BVC("bind_anon"),         SLAP_DISALLOW_BIND_ANON },
2334                 { BER_BVC("bind_simple"),       SLAP_DISALLOW_BIND_SIMPLE },
2335                 { BER_BVC("tls_2_anon"),                SLAP_DISALLOW_TLS_2_ANON },
2336                 { BER_BVC("tls_authc"),         SLAP_DISALLOW_TLS_AUTHC },
2337                 { BER_BVNULL, 0 }
2338         };
2339         if (c->op == SLAP_CONFIG_EMIT) {
2340                 return mask_to_verbs( disallowable_ops, global_disallows, &c->rvalue_vals );
2341         } else if ( c->op == LDAP_MOD_DELETE ) {
2342                 if ( !c->line ) {
2343                         global_disallows = 0;
2344                 } else {
2345                         disallows = verb_to_mask( c->line, disallowable_ops );
2346                         global_disallows ^= disallows;
2347                 }
2348                 return 0;
2349         }
2350         i = verbs_to_mask(c->argc, c->argv, disallowable_ops, &disallows);
2351         if ( i ) {
2352                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature", c->argv[0] );
2353                 Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2354                         c->log, c->cr_msg, c->argv[i]);
2355                 return(1);
2356         }
2357         global_disallows |= disallows;
2358         return(0);
2359 }
2360
2361 static int
2362 config_requires(ConfigArgs *c) {
2363         slap_mask_t requires = frontendDB->be_requires;
2364         int i, argc = c->argc;
2365         char **argv = c->argv;
2366
2367         slap_verbmasks requires_ops[] = {
2368                 { BER_BVC("bind"),              SLAP_REQUIRE_BIND },
2369                 { BER_BVC("LDAPv3"),            SLAP_REQUIRE_LDAP_V3 },
2370                 { BER_BVC("authc"),             SLAP_REQUIRE_AUTHC },
2371                 { BER_BVC("sasl"),              SLAP_REQUIRE_SASL },
2372                 { BER_BVC("strong"),            SLAP_REQUIRE_STRONG },
2373                 { BER_BVNULL, 0 }
2374         };
2375         if (c->op == SLAP_CONFIG_EMIT) {
2376                 return mask_to_verbs( requires_ops, c->be->be_requires, &c->rvalue_vals );
2377         } else if ( c->op == LDAP_MOD_DELETE ) {
2378                 if ( !c->line ) {
2379                         c->be->be_requires = 0;
2380                 } else {
2381                         requires = verb_to_mask( c->line, requires_ops );
2382                         c->be->be_requires ^= requires;
2383                 }
2384                 return 0;
2385         }
2386         /* "none" can only be first, to wipe out default/global values */
2387         if ( strcasecmp( c->argv[ 1 ], "none" ) == 0 ) {
2388                 argv++;
2389                 argc--;
2390                 requires = 0;
2391         }
2392         i = verbs_to_mask(argc, argv, requires_ops, &requires);
2393         if ( i ) {
2394                 if (strcasecmp( c->argv[ i ], "none" ) == 0 ) {
2395                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> \"none\" (#%d) must be listed first", c->argv[0], i - 1 );
2396                         Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2397                                 c->log, c->cr_msg, 0);
2398                 } else {
2399                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown feature #%d", c->argv[0], i - 1 );
2400                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2401                                 c->log, c->cr_msg, c->argv[i]);
2402                 }
2403                 return(1);
2404         }
2405         c->be->be_requires = requires;
2406         return(0);
2407 }
2408
2409 static slap_verbmasks   *loglevel_ops;
2410
2411 static int
2412 loglevel_init( void )
2413 {
2414         slap_verbmasks  lo[] = {
2415                 { BER_BVC("Any"),       -1 },
2416                 { BER_BVC("Trace"),     LDAP_DEBUG_TRACE },
2417                 { BER_BVC("Packets"),   LDAP_DEBUG_PACKETS },
2418                 { BER_BVC("Args"),      LDAP_DEBUG_ARGS },
2419                 { BER_BVC("Conns"),     LDAP_DEBUG_CONNS },
2420                 { BER_BVC("BER"),       LDAP_DEBUG_BER },
2421                 { BER_BVC("Filter"),    LDAP_DEBUG_FILTER },
2422                 { BER_BVC("Config"),    LDAP_DEBUG_CONFIG },
2423                 { BER_BVC("ACL"),       LDAP_DEBUG_ACL },
2424                 { BER_BVC("Stats"),     LDAP_DEBUG_STATS },
2425                 { BER_BVC("Stats2"),    LDAP_DEBUG_STATS2 },
2426                 { BER_BVC("Shell"),     LDAP_DEBUG_SHELL },
2427                 { BER_BVC("Parse"),     LDAP_DEBUG_PARSE },
2428 #if 0   /* no longer used (nor supported) */
2429                 { BER_BVC("Cache"),     LDAP_DEBUG_CACHE },
2430                 { BER_BVC("Index"),     LDAP_DEBUG_INDEX },
2431 #endif
2432                 { BER_BVC("Sync"),      LDAP_DEBUG_SYNC },
2433                 { BER_BVC("None"),      LDAP_DEBUG_NONE },
2434                 { BER_BVNULL,           0 }
2435         };
2436
2437         return slap_verbmasks_init( &loglevel_ops, lo );
2438 }
2439
2440 static void
2441 loglevel_destroy( void )
2442 {
2443         if ( loglevel_ops ) {
2444                 (void)slap_verbmasks_destroy( loglevel_ops );
2445         }
2446         loglevel_ops = NULL;
2447 }
2448
2449 static slap_mask_t      loglevel_ignore[] = { -1, 0 };
2450
2451 int
2452 slap_loglevel_register( slap_mask_t m, struct berval *s )
2453 {
2454         int     rc;
2455
2456         if ( loglevel_ops == NULL ) {
2457                 loglevel_init();
2458         }
2459
2460         rc = slap_verbmasks_append( &loglevel_ops, m, s, loglevel_ignore );
2461
2462         if ( rc != 0 ) {
2463                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_register(%lu, \"%s\") failed\n",
2464                         m, s->bv_val, 0 );
2465         }
2466
2467         return rc;
2468 }
2469
2470 int
2471 slap_loglevel_get( struct berval *s, int *l )
2472 {
2473         int             rc;
2474         slap_mask_t     m, i;
2475
2476         if ( loglevel_ops == NULL ) {
2477                 loglevel_init();
2478         }
2479
2480         for ( m = 0, i = 1; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2481                 m |= loglevel_ops[ i ].mask;
2482         }
2483
2484         for ( i = 1; m & i; i <<= 1 )
2485                 ;
2486
2487         if ( i == 0 ) {
2488                 return -1;
2489         }
2490
2491         rc = slap_verbmasks_append( &loglevel_ops, i, s, loglevel_ignore );
2492
2493         if ( rc != 0 ) {
2494                 Debug( LDAP_DEBUG_ANY, "slap_loglevel_get(%lu, \"%s\") failed\n",
2495                         i, s->bv_val, 0 );
2496
2497         } else {
2498                 *l = i;
2499         }
2500
2501         return rc;
2502 }
2503
2504 int
2505 str2loglevel( const char *s, int *l )
2506 {
2507         int     i;
2508
2509         if ( loglevel_ops == NULL ) {
2510                 loglevel_init();
2511         }
2512
2513         i = verb_to_mask( s, loglevel_ops );
2514
2515         if ( BER_BVISNULL( &loglevel_ops[ i ].word ) ) {
2516                 return -1;
2517         }
2518
2519         *l = loglevel_ops[ i ].mask;
2520
2521         return 0;
2522 }
2523
2524 const char *
2525 loglevel2str( int l )
2526 {
2527         struct berval   bv = BER_BVNULL;
2528
2529         loglevel2bv( l, &bv );
2530
2531         return bv.bv_val;
2532 }
2533
2534 int
2535 loglevel2bv( int l, struct berval *bv )
2536 {
2537         if ( loglevel_ops == NULL ) {
2538                 loglevel_init();
2539         }
2540
2541         BER_BVZERO( bv );
2542
2543         return enum_to_verb( loglevel_ops, l, bv ) == -1;
2544 }
2545
2546 int
2547 loglevel2bvarray( int l, BerVarray *bva )
2548 {
2549         if ( loglevel_ops == NULL ) {
2550                 loglevel_init();
2551         }
2552
2553         return mask_to_verbs( loglevel_ops, l, bva );
2554 }
2555
2556 int
2557 loglevel_print( FILE *out )
2558 {
2559         int     i;
2560
2561         if ( loglevel_ops == NULL ) {
2562                 loglevel_init();
2563         }
2564
2565         fprintf( out, "Installed log subsystems:\n\n" );
2566         for ( i = 0; !BER_BVISNULL( &loglevel_ops[ i ].word ); i++ ) {
2567                 fprintf( out, "\t%-30s (%lu)\n",
2568                         loglevel_ops[ i ].word.bv_val,
2569                         loglevel_ops[ i ].mask );
2570         }
2571
2572         fprintf( out, "\nNOTE: custom log subsystems may be later installed "
2573                 "by specific code\n\n" );
2574
2575         return 0;
2576 }
2577
2578 static int config_syslog;
2579
2580 static int
2581 config_loglevel(ConfigArgs *c) {
2582         int i;
2583
2584         if ( loglevel_ops == NULL ) {
2585                 loglevel_init();
2586         }
2587
2588         if (c->op == SLAP_CONFIG_EMIT) {
2589                 /* Get default or commandline slapd setting */
2590                 if ( ldap_syslog && !config_syslog )
2591                         config_syslog = ldap_syslog;
2592                 return loglevel2bvarray( config_syslog, &c->rvalue_vals );
2593
2594         } else if ( c->op == LDAP_MOD_DELETE ) {
2595                 if ( !c->line ) {
2596                         config_syslog = 0;
2597                 } else {
2598                         int level = verb_to_mask( c->line, loglevel_ops );
2599                         config_syslog ^= level;
2600                 }
2601                 if ( slapMode & SLAP_SERVER_MODE ) {
2602                         ldap_syslog = config_syslog;
2603                 }
2604                 return 0;
2605         }
2606
2607         for( i=1; i < c->argc; i++ ) {
2608                 int     level;
2609
2610                 if ( isdigit((unsigned char)c->argv[i][0]) || c->argv[i][0] == '-' ) {
2611                         if( lutil_atoi( &level, c->argv[i] ) != 0 ) {
2612                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse level", c->argv[0] );
2613                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2614                                         c->log, c->cr_msg, c->argv[i]);
2615                                 return( 1 );
2616                         }
2617                 } else {
2618                         if ( str2loglevel( c->argv[i], &level ) ) {
2619                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown level", c->argv[0] );
2620                                 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2621                                         c->log, c->cr_msg, c->argv[i]);
2622                                 return( 1 );
2623                         }
2624                 }
2625                 /* Explicitly setting a zero clears all the levels */
2626                 if ( level )
2627                         config_syslog |= level;
2628                 else
2629                         config_syslog = 0;
2630         }
2631         if ( slapMode & SLAP_SERVER_MODE ) {
2632                 ldap_syslog = config_syslog;
2633         }
2634         return(0);
2635 }
2636
2637 static int
2638 config_referral(ConfigArgs *c) {
2639         struct berval val;
2640         if (c->op == SLAP_CONFIG_EMIT) {
2641                 if ( default_referral ) {
2642                         value_add( &c->rvalue_vals, default_referral );
2643                         return 0;
2644                 } else {
2645                         return 1;
2646                 }
2647         } else if ( c->op == LDAP_MOD_DELETE ) {
2648                 if ( c->valx < 0 ) {
2649                         ber_bvarray_free( default_referral );
2650                         default_referral = NULL;
2651                 } else {
2652                         int i = c->valx;
2653                         ch_free( default_referral[i].bv_val );
2654                         for (; default_referral[i].bv_val; i++ )
2655                                 default_referral[i] = default_referral[i+1];
2656                 }
2657                 return 0;
2658         }
2659         if(validate_global_referral(c->argv[1])) {
2660                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2661                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2662                         c->log, c->cr_msg, c->argv[1]);
2663                 return(1);
2664         }
2665
2666         ber_str2bv(c->argv[1], 0, 0, &val);
2667         if(value_add_one(&default_referral, &val)) return(LDAP_OTHER);
2668         return(0);
2669 }
2670
2671 static struct {
2672         struct berval key;
2673         int off;
2674 } sec_keys[] = {
2675         { BER_BVC("ssf="), offsetof(slap_ssf_set_t, sss_ssf) },
2676         { BER_BVC("transport="), offsetof(slap_ssf_set_t, sss_transport) },
2677         { BER_BVC("tls="), offsetof(slap_ssf_set_t, sss_tls) },
2678         { BER_BVC("sasl="), offsetof(slap_ssf_set_t, sss_sasl) },
2679         { BER_BVC("update_ssf="), offsetof(slap_ssf_set_t, sss_update_ssf) },
2680         { BER_BVC("update_transport="), offsetof(slap_ssf_set_t, sss_update_transport) },
2681         { BER_BVC("update_tls="), offsetof(slap_ssf_set_t, sss_update_tls) },
2682         { BER_BVC("update_sasl="), offsetof(slap_ssf_set_t, sss_update_sasl) },
2683         { BER_BVC("simple_bind="), offsetof(slap_ssf_set_t, sss_simple_bind) },
2684         { BER_BVNULL, 0 }
2685 };
2686
2687 static int
2688 config_security(ConfigArgs *c) {
2689         slap_ssf_set_t *set = &c->be->be_ssf_set;
2690         char *next;
2691         int i, j;
2692         if (c->op == SLAP_CONFIG_EMIT) {
2693                 char numbuf[32];
2694                 struct berval bv;
2695                 slap_ssf_t *tgt;
2696                 int rc = 1;
2697
2698                 for (i=0; !BER_BVISNULL( &sec_keys[i].key ); i++) {
2699                         tgt = (slap_ssf_t *)((char *)set + sec_keys[i].off);
2700                         if ( *tgt ) {
2701                                 rc = 0;
2702                                 bv.bv_len = snprintf( numbuf, sizeof( numbuf ), "%u", *tgt );
2703                                 if ( bv.bv_len >= sizeof( numbuf ) ) {
2704                                         ber_bvarray_free_x( c->rvalue_vals, NULL );
2705                                         c->rvalue_vals = NULL;
2706                                         rc = 1;
2707                                         break;
2708                                 }
2709                                 bv.bv_len += sec_keys[i].key.bv_len;
2710                                 bv.bv_val = ch_malloc( bv.bv_len + 1);
2711                                 next = lutil_strcopy( bv.bv_val, sec_keys[i].key.bv_val );
2712                                 strcpy( next, numbuf );
2713                                 ber_bvarray_add( &c->rvalue_vals, &bv );
2714                         }
2715                 }
2716                 return rc;
2717         }
2718         for(i = 1; i < c->argc; i++) {
2719                 slap_ssf_t *tgt = NULL;
2720                 char *src = NULL;
2721                 for ( j=0; !BER_BVISNULL( &sec_keys[j].key ); j++ ) {
2722                         if(!strncasecmp(c->argv[i], sec_keys[j].key.bv_val,
2723                                 sec_keys[j].key.bv_len)) {
2724                                 src = c->argv[i] + sec_keys[j].key.bv_len;
2725                                 tgt = (slap_ssf_t *)((char *)set + sec_keys[j].off);
2726                                 break;
2727                         }
2728                 }
2729                 if ( !tgt ) {
2730                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unknown factor", c->argv[0] );
2731                         Debug(LDAP_DEBUG_ANY, "%s: %s %s\n",
2732                                 c->log, c->cr_msg, c->argv[i]);
2733                         return(1);
2734                 }
2735
2736                 if ( lutil_atou( tgt, src ) != 0 ) {
2737                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> unable to parse factor", c->argv[0] );
2738                         Debug(LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
2739                                 c->log, c->cr_msg, c->argv[i]);
2740                         return(1);
2741                 }
2742         }
2743         return(0);
2744 }
2745
2746 char *
2747 anlist_unparse( AttributeName *an, char *ptr, ber_len_t buflen ) {
2748         int comma = 0;
2749         char *start = ptr;
2750
2751         for (; !BER_BVISNULL( &an->an_name ); an++) {
2752                 /* if buflen == 0, assume the buffer size has been 
2753                  * already checked otherwise */
2754                 if ( buflen > 0 && buflen - ( ptr - start ) < comma + an->an_name.bv_len ) return NULL;
2755                 if ( comma ) *ptr++ = ',';
2756                 ptr = lutil_strcopy( ptr, an->an_name.bv_val );
2757                 comma = 1;
2758         }
2759         return ptr;
2760 }
2761
2762 static int
2763 config_updatedn(ConfigArgs *c) {
2764         if (c->op == SLAP_CONFIG_EMIT) {
2765                 if (!BER_BVISEMPTY(&c->be->be_update_ndn)) {
2766                         value_add_one(&c->rvalue_vals, &c->be->be_update_ndn);
2767                         value_add_one(&c->rvalue_nvals, &c->be->be_update_ndn);
2768                         return 0;
2769                 }
2770                 return 1;
2771         } else if ( c->op == LDAP_MOD_DELETE ) {
2772                 ch_free( c->be->be_update_ndn.bv_val );
2773                 BER_BVZERO( &c->be->be_update_ndn );
2774                 SLAP_DBFLAGS(c->be) ^= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SLURP_SHADOW);
2775                 return 0;
2776         }
2777         if(SLAP_SHADOW(c->be)) {
2778                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> database already shadowed", c->argv[0] );
2779                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2780                         c->log, c->cr_msg, 0);
2781                 return(1);
2782         }
2783
2784         ber_memfree_x( c->value_dn.bv_val, NULL );
2785         if ( !BER_BVISNULL( &c->be->be_update_ndn ) ) {
2786                 ber_memfree_x( c->be->be_update_ndn.bv_val, NULL );
2787         }
2788         c->be->be_update_ndn = c->value_ndn;
2789         BER_BVZERO( &c->value_dn );
2790         BER_BVZERO( &c->value_ndn );
2791
2792         return config_slurp_shadow( c );
2793 }
2794
2795 int
2796 config_shadow( ConfigArgs *c, int flag )
2797 {
2798         char    *notallowed = NULL;
2799
2800         if ( c->be == frontendDB ) {
2801                 notallowed = "frontend";
2802
2803         } else if ( SLAP_MONITOR(c->be) ) {
2804                 notallowed = "monitor";
2805         }
2806
2807         if ( notallowed != NULL ) {
2808                 Debug( LDAP_DEBUG_ANY, "%s: %s database cannot be shadow.\n", c->log, notallowed, 0 );
2809                 return 1;
2810         }
2811
2812         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SINGLE_SHADOW | flag);
2813
2814         return 0;
2815 }
2816
2817 static int
2818 config_updateref(ConfigArgs *c) {
2819         struct berval val;
2820         if (c->op == SLAP_CONFIG_EMIT) {
2821                 if ( c->be->be_update_refs ) {
2822                         value_add( &c->rvalue_vals, c->be->be_update_refs );
2823                         return 0;
2824                 } else {
2825                         return 1;
2826                 }
2827         } else if ( c->op == LDAP_MOD_DELETE ) {
2828                 if ( c->valx < 0 ) {
2829                         ber_bvarray_free( c->be->be_update_refs );
2830                         c->be->be_update_refs = NULL;
2831                 } else {
2832                         int i = c->valx;
2833                         ch_free( c->be->be_update_refs[i].bv_val );
2834                         for (; c->be->be_update_refs[i].bv_val; i++)
2835                                 c->be->be_update_refs[i] = c->be->be_update_refs[i+1];
2836                 }
2837                 return 0;
2838         }
2839         if(!SLAP_SHADOW(c->be) && !c->be->be_syncinfo) {
2840                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> must appear after syncrepl or updatedn",
2841                         c->argv[0] );
2842                 Debug(LDAP_DEBUG_ANY, "%s: %s\n",
2843                         c->log, c->cr_msg, 0);
2844                 return(1);
2845         }
2846
2847         if(validate_global_referral(c->argv[1])) {
2848                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid URL", c->argv[0] );
2849                 Debug(LDAP_DEBUG_ANY, "%s: %s (%s)\n",
2850                         c->log, c->cr_msg, c->argv[1]);
2851                 return(1);
2852         }
2853         ber_str2bv(c->argv[1], 0, 0, &val);
2854         if(value_add_one(&c->be->be_update_refs, &val)) return(LDAP_OTHER);
2855         return(0);
2856 }
2857
2858 static int
2859 config_obsolete(ConfigArgs *c) {
2860         if (c->op == SLAP_CONFIG_EMIT)
2861                 return 1;
2862
2863         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> keyword is obsolete (ignored)",
2864                 c->argv[0] );
2865         Debug(LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0);
2866         return(0);
2867 }
2868
2869 static int
2870 config_include(ConfigArgs *c) {
2871         int savelineno = c->lineno;
2872         int rc;
2873         ConfigFile *cf;
2874         ConfigFile *cfsave = cfn;
2875         ConfigFile *cf2 = NULL;
2876
2877         /* Leftover from RE23. No dynamic config for include files */
2878         if ( c->op == SLAP_CONFIG_EMIT || c->op == LDAP_MOD_DELETE )
2879                 return 1;
2880
2881         cf = ch_calloc( 1, sizeof(ConfigFile));
2882         if ( cfn->c_kids ) {
2883                 for (cf2=cfn->c_kids; cf2 && cf2->c_sibs; cf2=cf2->c_sibs) ;
2884                 cf2->c_sibs = cf;
2885         } else {
2886                 cfn->c_kids = cf;
2887         }
2888         cfn = cf;
2889         ber_str2bv( c->argv[1], 0, 1, &cf->c_file );
2890         rc = read_config_file(c->argv[1], c->depth + 1, c, config_back_cf_table);
2891         c->lineno = savelineno - 1;
2892         cfn = cfsave;
2893         if ( rc ) {
2894                 if ( cf2 ) cf2->c_sibs = NULL;
2895                 else cfn->c_kids = NULL;
2896                 ch_free( cf->c_file.bv_val );
2897                 ch_free( cf );
2898         } else {
2899                 c->private = cf;
2900         }
2901         return(rc);
2902 }
2903
2904 #ifdef HAVE_TLS
2905 static int
2906 config_tls_option(ConfigArgs *c) {
2907         int flag;
2908         LDAP *ld = slap_tls_ld;
2909         switch(c->type) {
2910         case CFG_TLS_RAND:      flag = LDAP_OPT_X_TLS_RANDOM_FILE;      ld = NULL; break;
2911         case CFG_TLS_CIPHER:    flag = LDAP_OPT_X_TLS_CIPHER_SUITE;     break;
2912         case CFG_TLS_CERT_FILE: flag = LDAP_OPT_X_TLS_CERTFILE;         break;  
2913         case CFG_TLS_CERT_KEY:  flag = LDAP_OPT_X_TLS_KEYFILE;          break;
2914         case CFG_TLS_CA_PATH:   flag = LDAP_OPT_X_TLS_CACERTDIR;        break;
2915         case CFG_TLS_CA_FILE:   flag = LDAP_OPT_X_TLS_CACERTFILE;       break;
2916         case CFG_TLS_DH_FILE:   flag = LDAP_OPT_X_TLS_DHFILE;   break;
2917 #ifdef HAVE_GNUTLS
2918         case CFG_TLS_CRL_FILE:  flag = LDAP_OPT_X_TLS_CRLFILE;  break;
2919 #endif
2920         default:                Debug(LDAP_DEBUG_ANY, "%s: "
2921                                         "unknown tls_option <0x%x>\n",
2922                                         c->log, c->type, 0);
2923                 return 1;
2924         }
2925         if (c->op == SLAP_CONFIG_EMIT) {
2926                 return ldap_pvt_tls_get_option( ld, flag, &c->value_string );
2927         } else if ( c->op == LDAP_MOD_DELETE ) {
2928                 return ldap_pvt_tls_set_option( ld, flag, NULL );
2929         }
2930         ch_free(c->value_string);
2931         return(ldap_pvt_tls_set_option(ld, flag, c->argv[1]));
2932 }
2933
2934 /* FIXME: this ought to be provided by libldap */
2935 static int
2936 config_tls_config(ConfigArgs *c) {
2937         int i, flag;
2938         switch(c->type) {
2939         case CFG_TLS_CRLCHECK:  flag = LDAP_OPT_X_TLS_CRLCHECK; break;
2940         case CFG_TLS_VERIFY:    flag = LDAP_OPT_X_TLS_REQUIRE_CERT; break;
2941         default:
2942                 Debug(LDAP_DEBUG_ANY, "%s: "
2943                                 "unknown tls_option <0x%x>\n",
2944                                 c->log, c->type, 0);
2945                 return 1;
2946         }
2947         if (c->op == SLAP_CONFIG_EMIT) {
2948                 return slap_tls_get_config( slap_tls_ld, flag, &c->value_string );
2949         } else if ( c->op == LDAP_MOD_DELETE ) {
2950                 int i = 0;
2951                 return ldap_pvt_tls_set_option( slap_tls_ld, flag, &i );
2952         }
2953         ch_free( c->value_string );
2954         if ( isdigit( (unsigned char)c->argv[1][0] ) ) {
2955                 if ( lutil_atoi( &i, c->argv[1] ) != 0 ) {
2956                         Debug(LDAP_DEBUG_ANY, "%s: "
2957                                 "unable to parse %s \"%s\"\n",
2958                                 c->log, c->argv[0], c->argv[1] );
2959                         return 1;
2960                 }
2961                 return(ldap_pvt_tls_set_option(slap_tls_ld, flag, &i));
2962         } else {
2963                 return(ldap_int_tls_config(slap_tls_ld, flag, c->argv[1]));
2964         }
2965 }
2966 #endif
2967
2968 static CfEntryInfo *
2969 config_find_base( CfEntryInfo *root, struct berval *dn, CfEntryInfo **last )
2970 {
2971         struct berval cdn;
2972         char *c;
2973
2974         if ( !root ) {
2975                 *last = NULL;
2976                 return NULL;
2977         }
2978
2979         if ( dn_match( &root->ce_entry->e_nname, dn ))
2980                 return root;
2981
2982         c = dn->bv_val+dn->bv_len;
2983         for (;*c != ',';c--);
2984
2985         while(root) {
2986                 *last = root;
2987                 for (--c;c>dn->bv_val && *c != ',';c--);
2988                 cdn.bv_val = c;
2989                 if ( *c == ',' )
2990                         cdn.bv_val++;
2991                 cdn.bv_len = dn->bv_len - (cdn.bv_val - dn->bv_val);
2992
2993                 root = root->ce_kids;
2994
2995                 for (;root;root=root->ce_sibs) {
2996                         if ( dn_match( &root->ce_entry->e_nname, &cdn )) {
2997                                 if ( cdn.bv_val == dn->bv_val ) {
2998                                         return root;
2999                                 }
3000                                 break;
3001                         }
3002                 }
3003         }
3004         return root;
3005 }
3006
3007 typedef struct setup_cookie {
3008         CfBackInfo *cfb;
3009         ConfigArgs *ca;
3010         Entry *frontend;
3011         Entry *config;
3012         int     got_frontend;
3013         int got_config;
3014 } setup_cookie;
3015
3016 static int
3017 config_ldif_resp( Operation *op, SlapReply *rs )
3018 {
3019         if ( rs->sr_type == REP_SEARCH ) {
3020                 setup_cookie *sc = op->o_callback->sc_private;
3021
3022                 sc->cfb->cb_got_ldif = 1;
3023                 /* Does the frontend exist? */
3024                 if ( !sc->got_frontend ) {
3025                         if ( !strncmp( rs->sr_entry->e_nname.bv_val,
3026                                 "olcDatabase", STRLENOF( "olcDatabase" ))) {
3027                                 if ( strncmp( rs->sr_entry->e_nname.bv_val +
3028                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
3029                                         STRLENOF( "={-1}frontend" ))) {
3030                                         struct berval rdn;
3031                                         int i = op->o_noop;
3032                                         sc->ca->be = frontendDB;
3033                                         sc->ca->bi = frontendDB->bd_info;
3034                                         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
3035                                         rdn.bv_val = sc->ca->log;
3036                                         rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3037                                                 "%s=" SLAP_X_ORDERED_FMT "%s",
3038                                                 cfAd_database->ad_cname.bv_val, -1,
3039                                                 sc->ca->bi->bi_type);
3040                                         op->o_noop = 1;
3041                                         sc->frontend = config_build_entry( op, rs,
3042                                                 sc->cfb->cb_root, sc->ca, &rdn, &CFOC_DATABASE,
3043                                                 sc->ca->be->be_cf_ocs );
3044                                         op->o_noop = i;
3045                                         sc->got_frontend++;
3046                                 } else {
3047                                         sc->got_frontend++;
3048                                         goto ok;
3049                                 }
3050                         }
3051                 }
3052                 /* Does the configDB exist? */
3053                 if ( sc->got_frontend && !sc->got_config &&
3054                         !strncmp( rs->sr_entry->e_nname.bv_val,
3055                         "olcDatabase", STRLENOF( "olcDatabase" ))) {
3056                         if ( strncmp( rs->sr_entry->e_nname.bv_val +
3057                                 STRLENOF( "olcDatabase" ), "={0}config",
3058                                 STRLENOF( "={0}config" ))) {
3059                                 struct berval rdn;
3060                                 int i = op->o_noop;
3061                                 sc->ca->be = LDAP_STAILQ_FIRST( &backendDB );
3062                                 sc->ca->bi = sc->ca->be->bd_info;
3063                                 rdn.bv_val = sc->ca->log;
3064                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( sc->ca->log ),
3065                                         "%s=" SLAP_X_ORDERED_FMT "%s",
3066                                         cfAd_database->ad_cname.bv_val, 0,
3067                                         sc->ca->bi->bi_type);
3068                                 op->o_noop = 1;
3069                                 sc->config = config_build_entry( op, rs, sc->cfb->cb_root,
3070                                         sc->ca, &rdn, &CFOC_DATABASE, sc->ca->be->be_cf_ocs );
3071                                 op->o_noop = i;
3072                         }
3073                         sc->got_config++;
3074                 }
3075
3076 ok:
3077                 rs->sr_err = config_add_internal( sc->cfb, rs->sr_entry, sc->ca, NULL, NULL, NULL );
3078                 if ( rs->sr_err != LDAP_SUCCESS ) {
3079                         Debug( LDAP_DEBUG_ANY, "config error processing %s: %s\n",
3080                                 rs->sr_entry->e_name.bv_val, sc->ca->cr_msg, 0 );
3081                 }
3082         }
3083         return rs->sr_err;
3084 }
3085
3086 /* Configure and read the underlying back-ldif store */
3087 static int
3088 config_setup_ldif( BackendDB *be, const char *dir, int readit ) {
3089         CfBackInfo *cfb = be->be_private;
3090         ConfigArgs c = {0};
3091         ConfigTable *ct;
3092         char *argv[3];
3093         int rc = 0;
3094         setup_cookie sc;
3095         slap_callback cb = { NULL, config_ldif_resp, NULL, NULL };
3096         Connection conn = {0};
3097         OperationBuffer opbuf;
3098         Operation *op;
3099         SlapReply rs = {REP_RESULT};
3100         Filter filter = { LDAP_FILTER_PRESENT };
3101         struct berval filterstr = BER_BVC("(objectclass=*)");
3102         struct stat st;
3103
3104         /* Is the config directory available? */
3105         if ( stat( dir, &st ) < 0 ) {
3106                 /* No, so don't bother using the backing store.
3107                  * All changes will be in-memory only.
3108                  */
3109                 return 0;
3110         }
3111                 
3112         cfb->cb_db.bd_info = backend_info( "ldif" );
3113         if ( !cfb->cb_db.bd_info )
3114                 return 0;       /* FIXME: eventually this will be a fatal error */
3115
3116         if ( backend_db_init( "ldif", &cfb->cb_db, -1, NULL ) == NULL )
3117                 return 1;
3118
3119         cfb->cb_db.be_suffix = be->be_suffix;
3120         cfb->cb_db.be_nsuffix = be->be_nsuffix;
3121
3122         /* The suffix is always "cn=config". The underlying DB's rootdn
3123          * is always the same as the suffix.
3124          */
3125         cfb->cb_db.be_rootdn = be->be_suffix[0];
3126         cfb->cb_db.be_rootndn = be->be_nsuffix[0];
3127
3128         ber_str2bv( dir, 0, 1, &cfdir );
3129
3130         c.be = &cfb->cb_db;
3131         c.fname = "slapd";
3132         c.argc = 2;
3133         argv[0] = "directory";
3134         argv[1] = (char *)dir;
3135         argv[2] = NULL;
3136         c.argv = argv;
3137         c.reply.err = 0;
3138         c.reply.msg[0] = 0;
3139         c.table = Cft_Database;
3140
3141         ct = config_find_keyword( c.be->be_cf_ocs->co_table, &c );
3142         if ( !ct )
3143                 return 1;
3144
3145         if ( config_add_vals( ct, &c ))
3146                 return 1;
3147
3148         if ( backend_startup_one( &cfb->cb_db, &c.reply ))
3149                 return 1;
3150
3151         if ( readit ) {
3152                 void *thrctx = ldap_pvt_thread_pool_context();
3153                 int prev_DN_strict;
3154
3155                 connection_fake_init( &conn, &opbuf, thrctx );
3156                 op = &opbuf.ob_op;
3157
3158                 filter.f_desc = slap_schema.si_ad_objectClass;
3159
3160                 op->o_tag = LDAP_REQ_SEARCH;
3161
3162                 op->ors_filter = &filter;
3163                 op->ors_filterstr = filterstr;
3164                 op->ors_scope = LDAP_SCOPE_SUBTREE;
3165
3166                 op->o_dn = c.be->be_rootdn;
3167                 op->o_ndn = c.be->be_rootndn;
3168
3169                 op->o_req_dn = be->be_suffix[0];
3170                 op->o_req_ndn = be->be_nsuffix[0];
3171
3172                 op->ors_tlimit = SLAP_NO_LIMIT;
3173                 op->ors_slimit = SLAP_NO_LIMIT;
3174
3175                 op->ors_attrs = slap_anlist_all_attributes;
3176                 op->ors_attrsonly = 0;
3177
3178                 op->o_callback = &cb;
3179                 sc.cfb = cfb;
3180                 sc.ca = &c;
3181                 cb.sc_private = &sc;
3182                 sc.got_frontend = 0;
3183                 sc.got_config = 0;
3184                 sc.frontend = NULL;
3185                 sc.config = NULL;
3186
3187                 op->o_bd = &cfb->cb_db;
3188                 
3189                 /* Allow unknown attrs in DNs */
3190                 prev_DN_strict = slap_DN_strict;
3191                 slap_DN_strict = 0;
3192
3193                 rc = op->o_bd->be_search( op, &rs );
3194
3195                 /* Restore normal DN validation */
3196                 slap_DN_strict = prev_DN_strict;
3197
3198                 op->o_tag = LDAP_REQ_ADD;
3199                 if ( rc == LDAP_SUCCESS && sc.frontend ) {
3200                         op->ora_e = sc.frontend;
3201                         rc = op->o_bd->be_add( op, &rs );
3202                 }
3203                 if ( rc == LDAP_SUCCESS && sc.config ) {
3204                         op->ora_e = sc.config;
3205                         rc = op->o_bd->be_add( op, &rs );
3206                 }
3207                 ldap_pvt_thread_pool_context_reset( thrctx );
3208         }
3209
3210         /* ITS#4194 - only use if it's present, or we're converting. */
3211         if ( !readit || rc == LDAP_SUCCESS )
3212                 cfb->cb_use_ldif = 1;
3213
3214         return rc;
3215 }
3216
3217 static int
3218 CfOc_cmp( const void *c1, const void *c2 ) {
3219         const ConfigOCs *co1 = c1;
3220         const ConfigOCs *co2 = c2;
3221
3222         return ber_bvcmp( co1->co_name, co2->co_name );
3223 }
3224
3225 int
3226 config_register_schema(ConfigTable *ct, ConfigOCs *ocs) {
3227         int i;
3228
3229         i = init_config_attrs( ct );
3230         if ( i ) return i;
3231
3232         /* set up the objectclasses */
3233         i = init_config_ocs( ocs );
3234         if ( i ) return i;
3235
3236         for (i=0; ocs[i].co_def; i++) {
3237                 if ( ocs[i].co_oc ) {
3238                         ocs[i].co_name = &ocs[i].co_oc->soc_cname;
3239                         if ( !ocs[i].co_table )
3240                                 ocs[i].co_table = ct;
3241                         avl_insert( &CfOcTree, &ocs[i], CfOc_cmp, avl_dup_error );
3242                 }
3243         }
3244         return 0;
3245 }
3246
3247 int
3248 read_config(const char *fname, const char *dir) {
3249         BackendDB *be;
3250         CfBackInfo *cfb;
3251         const char *cfdir, *cfname;
3252         int rc;
3253
3254         /* Setup the config backend */
3255         be = backend_db_init( "config", NULL, 0, NULL );
3256         if ( !be )
3257                 return 1;
3258
3259         cfb = be->be_private;
3260         be->be_dfltaccess = ACL_NONE;
3261
3262         /* If no .conf, or a dir was specified, setup the dir */
3263         if ( !fname || dir ) {
3264                 if ( dir ) {
3265                         /* If explicitly given, check for existence */
3266                         struct stat st;
3267
3268                         if ( stat( dir, &st ) < 0 ) {
3269                                 Debug( LDAP_DEBUG_ANY,
3270                                         "invalid config directory %s, error %d\n",
3271                                                 dir, errno, 0 );
3272                                 return 1;
3273                         }
3274                         cfdir = dir;
3275                 } else {
3276                         cfdir = SLAPD_DEFAULT_CONFIGDIR;
3277                 }
3278                 /* if fname is defaulted, try reading .d */
3279                 rc = config_setup_ldif( be, cfdir, !fname );
3280
3281                 if ( rc ) {
3282                         /* It may be OK if the base object doesn't exist yet. */
3283                         if ( rc != LDAP_NO_SUCH_OBJECT )
3284                                 return 1;
3285                         /* ITS#4194: But if dir was specified and no fname,
3286                          * then we were supposed to read the dir. Unless we're
3287                          * trying to slapadd the dir...
3288                          */
3289                         if ( dir && !fname ) {
3290                                 if ( slapMode & (SLAP_SERVER_MODE|SLAP_TOOL_READMAIN|SLAP_TOOL_READONLY))
3291                                         return 1;
3292                                 /* Assume it's slapadd with a config dir, let it continue */
3293                                 rc = 0;
3294                                 cfb->cb_got_ldif = 1;
3295                                 cfb->cb_use_ldif = 1;
3296                                 goto done;
3297                         }
3298                 }
3299
3300                 /* If we read the config from back-ldif, nothing to do here */
3301                 if ( cfb->cb_got_ldif ) {
3302                         rc = 0;
3303                         goto done;
3304                 }
3305         }
3306
3307         if ( fname )
3308                 cfname = fname;
3309         else
3310                 cfname = SLAPD_DEFAULT_CONFIGFILE;
3311
3312         rc = read_config_file(cfname, 0, NULL, config_back_cf_table);
3313
3314         if ( rc == 0 )
3315                 ber_str2bv( cfname, 0, 1, &cfb->cb_config->c_file );
3316
3317 done:
3318         if ( rc == 0 && BER_BVISNULL( &frontendDB->be_schemadn ) ) {
3319                 ber_str2bv( SLAPD_SCHEMA_DN, STRLENOF( SLAPD_SCHEMA_DN ), 1,
3320                         &frontendDB->be_schemadn );
3321                 rc = dnNormalize( 0, NULL, NULL, &frontendDB->be_schemadn, &frontendDB->be_schemandn, NULL );
3322                 if ( rc != LDAP_SUCCESS ) {
3323                         Debug(LDAP_DEBUG_ANY, "read_config: "
3324                                 "unable to normalize default schema DN \"%s\"\n",
3325                                 frontendDB->be_schemadn.bv_val, 0, 0 );
3326                         /* must not happen */
3327                         assert( 0 );
3328                 }
3329         }
3330         return rc;
3331 }
3332
3333 static int
3334 config_back_bind( Operation *op, SlapReply *rs )
3335 {
3336         if ( be_isroot_pw( op ) ) {
3337                 ber_dupbv( &op->orb_edn, be_root_dn( op->o_bd ));
3338                 /* frontend sends result */
3339                 return LDAP_SUCCESS;
3340         }
3341
3342         rs->sr_err = LDAP_INVALID_CREDENTIALS;
3343         send_ldap_result( op, rs );
3344
3345         return rs->sr_err;
3346 }
3347
3348 static int
3349 config_send( Operation *op, SlapReply *rs, CfEntryInfo *ce, int depth )
3350 {
3351         int rc = 0;
3352
3353         if ( test_filter( op, ce->ce_entry, op->ors_filter ) == LDAP_COMPARE_TRUE )
3354         {
3355                 rs->sr_attrs = op->ors_attrs;
3356                 rs->sr_entry = ce->ce_entry;
3357                 rs->sr_flags = 0;
3358                 rc = send_search_entry( op, rs );
3359         }
3360         if ( op->ors_scope == LDAP_SCOPE_SUBTREE ) {
3361                 if ( ce->ce_kids ) {
3362                         rc = config_send( op, rs, ce->ce_kids, 1 );
3363                         if ( rc ) return rc;
3364                 }
3365                 if ( depth ) {
3366                         for (ce=ce->ce_sibs; ce; ce=ce->ce_sibs) {
3367                                 rc = config_send( op, rs, ce, 0 );
3368                                 if ( rc ) break;
3369                         }
3370                 }
3371         }
3372         return rc;
3373 }
3374
3375 static ConfigTable *
3376 config_find_table( ConfigOCs **colst, int nocs, AttributeDescription *ad,
3377         ConfigArgs *ca )
3378 {
3379         int i, j;
3380
3381         for (j=0; j<nocs; j++) {
3382                 for (i=0; colst[j]->co_table[i].name; i++)
3383                         if ( colst[j]->co_table[i].ad == ad ) {
3384                                 ca->table = colst[j]->co_type;
3385                                 return &colst[j]->co_table[i];
3386                         }
3387         }
3388         return NULL;
3389 }
3390
3391 /* Sort the attributes of the entry according to the order defined
3392  * in the objectclass, with required attributes occurring before
3393  * allowed attributes. For any attributes with sequencing dependencies
3394  * (e.g., rootDN must be defined after suffix) the objectclass must
3395  * list the attributes in the desired sequence.
3396  */
3397 static void
3398 sort_attrs( Entry *e, ConfigOCs **colst, int nocs )
3399 {
3400         Attribute *a, *head = NULL, *tail = NULL, **prev;
3401         int i, j;
3402
3403         for (i=0; i<nocs; i++) {
3404                 if ( colst[i]->co_oc->soc_required ) {
3405                         AttributeType **at = colst[i]->co_oc->soc_required;
3406                         for (j=0; at[j]; j++) {
3407                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3408                                         prev = &(*prev)->a_next, a=a->a_next) {
3409                                         if ( a->a_desc == at[j]->sat_ad ) {
3410                                                 *prev = a->a_next;
3411                                                 if (!head) {
3412                                                         head = a;
3413                                                         tail = a;
3414                                                 } else {
3415                                                         tail->a_next = a;
3416                                                         tail = a;
3417                                                 }
3418                                                 break;
3419                                         }
3420                                 }
3421                         }
3422                 }
3423                 if ( colst[i]->co_oc->soc_allowed ) {
3424                         AttributeType **at = colst[i]->co_oc->soc_allowed;
3425                         for (j=0; at[j]; j++) {
3426                                 for (a=e->e_attrs, prev=&e->e_attrs; a;
3427                                         prev = &(*prev)->a_next, a=a->a_next) {
3428                                         if ( a->a_desc == at[j]->sat_ad ) {
3429                                                 *prev = a->a_next;
3430                                                 if (!head) {
3431                                                         head = a;
3432                                                         tail = a;
3433                                                 } else {
3434                                                         tail->a_next = a;
3435                                                         tail = a;
3436                                                 }
3437                                                 break;
3438                                         }
3439                                 }
3440                         }
3441                 }
3442         }
3443         if ( tail ) {
3444                 tail->a_next = e->e_attrs;
3445                 e->e_attrs = head;
3446         }
3447 }
3448
3449 static int
3450 check_vals( ConfigTable *ct, ConfigArgs *ca, void *ptr, int isAttr )
3451 {
3452         Attribute *a = NULL;
3453         AttributeDescription *ad;
3454         BerVarray vals;
3455
3456         int i, rc = 0;
3457
3458         if ( isAttr ) {
3459                 a = ptr;
3460                 ad = a->a_desc;
3461                 vals = a->a_vals;
3462         } else {
3463                 Modifications *ml = ptr;
3464                 ad = ml->sml_desc;
3465                 vals = ml->sml_values;
3466         }
3467
3468         if ( a && ( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL )) {
3469                 rc = ordered_value_sort( a, 1 );
3470                 if ( rc ) {
3471                         snprintf(ca->cr_msg, sizeof( ca->cr_msg ), "ordered_value_sort failed on attr %s\n",
3472                                 ad->ad_cname.bv_val );
3473                         return rc;
3474                 }
3475         }
3476         for ( i=0; vals[i].bv_val; i++ ) {
3477                 ca->line = vals[i].bv_val;
3478                 if (( ad->ad_type->sat_flags & SLAP_AT_ORDERED_VAL ) &&
3479                         ca->line[0] == '{' ) {
3480                         char *idx = strchr( ca->line, '}' );
3481                         if ( idx ) ca->line = idx+1;
3482                 }
3483                 rc = config_parse_vals( ct, ca, i );
3484                 if ( rc ) {
3485                         break;
3486                 }
3487         }
3488         return rc;
3489 }
3490
3491 static int
3492 config_rename_attr( SlapReply *rs, Entry *e, struct berval *rdn,
3493         Attribute **at )
3494 {
3495         struct berval rtype, rval;
3496         Attribute *a;
3497         AttributeDescription *ad = NULL;
3498
3499         dnRdn( &e->e_name, rdn );
3500         rval.bv_val = strchr(rdn->bv_val, '=' ) + 1;
3501         rval.bv_len = rdn->bv_len - (rval.bv_val - rdn->bv_val);
3502         rtype.bv_val = rdn->bv_val;
3503         rtype.bv_len = rval.bv_val - rtype.bv_val - 1;
3504
3505         /* Find attr */
3506         slap_bv2ad( &rtype, &ad, &rs->sr_text );
3507         a = attr_find( e->e_attrs, ad );
3508         if (!a ) return LDAP_NAMING_VIOLATION;
3509         *at = a;
3510
3511         return 0;
3512 }
3513
3514 static void
3515 config_rename_kids( CfEntryInfo *ce )
3516 {
3517         CfEntryInfo *ce2;
3518         struct berval rdn, nrdn;
3519
3520         for (ce2 = ce->ce_kids; ce2; ce2 = ce2->ce_sibs) {
3521                 dnRdn ( &ce2->ce_entry->e_name, &rdn );
3522                 dnRdn ( &ce2->ce_entry->e_nname, &nrdn );
3523                 free( ce2->ce_entry->e_name.bv_val );
3524                 free( ce2->ce_entry->e_nname.bv_val );
3525                 build_new_dn( &ce2->ce_entry->e_name, &ce->ce_entry->e_name,
3526                         &rdn, NULL );
3527                 build_new_dn( &ce2->ce_entry->e_nname, &ce->ce_entry->e_nname,
3528                         &nrdn, NULL );
3529                 config_rename_kids( ce2 );
3530         }
3531 }
3532
3533 static int
3534 config_rename_one( Operation *op, SlapReply *rs, Entry *e,
3535         CfEntryInfo *parent, Attribute *a, struct berval *newrdn,
3536         struct berval *nnewrdn, int use_ldif )
3537 {
3538         char *ptr1;
3539         int rc = 0;
3540         struct berval odn, ondn;
3541
3542         odn = e->e_name;
3543         ondn = e->e_nname;
3544         build_new_dn( &e->e_name, &parent->ce_entry->e_name, newrdn, NULL );
3545         build_new_dn( &e->e_nname, &parent->ce_entry->e_nname, nnewrdn, NULL );
3546
3547         /* Replace attr */
3548         free( a->a_vals[0].bv_val );
3549         ptr1 = strchr( newrdn->bv_val, '=' ) + 1;
3550         a->a_vals[0].bv_len = newrdn->bv_len - (ptr1 - newrdn->bv_val);
3551         a->a_vals[0].bv_val = ch_malloc( a->a_vals[0].bv_len + 1 );
3552         strcpy( a->a_vals[0].bv_val, ptr1 );
3553
3554         if ( a->a_nvals != a->a_vals ) {
3555                 free( a->a_nvals[0].bv_val );
3556                 ptr1 = strchr( nnewrdn->bv_val, '=' ) + 1;
3557                 a->a_nvals[0].bv_len = nnewrdn->bv_len - (ptr1 - nnewrdn->bv_val);
3558                 a->a_nvals[0].bv_val = ch_malloc( a->a_nvals[0].bv_len + 1 );
3559                 strcpy( a->a_nvals[0].bv_val, ptr1 );
3560         }
3561         if ( use_ldif ) {
3562                 CfBackInfo *cfb = (CfBackInfo *)op->o_bd->be_private;
3563                 BackendDB *be = op->o_bd;
3564                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
3565                 struct berval dn, ndn, xdn, xndn;
3566
3567                 op->o_bd = &cfb->cb_db;
3568
3569                 /* Save current rootdn; use the underlying DB's rootdn */
3570                 dn = op->o_dn;
3571                 ndn = op->o_ndn;
3572                 xdn = op->o_req_dn;
3573                 xndn = op->o_req_ndn;
3574                 op->o_dn = op->o_bd->be_rootdn;
3575                 op->o_ndn = op->o_bd->be_rootndn;
3576                 op->o_req_dn = odn;
3577                 op->o_req_ndn = ondn;
3578
3579                 scp = op->o_callback;
3580                 op->o_callback = &sc;
3581                 op->orr_newrdn = *newrdn;
3582                 op->orr_nnewrdn = *nnewrdn;
3583                 op->orr_newSup = NULL;
3584                 op->orr_nnewSup = NULL;
3585                 op->orr_deleteoldrdn = 1;
3586                 op->orr_modlist = NULL;
3587                 slap_modrdn2mods( op, rs );
3588                 slap_mods_opattrs( op, &op->orr_modlist, 1 );
3589                 rc = op->o_bd->be_modrdn( op, rs );
3590                 slap_mods_free( op->orr_modlist, 1 );
3591
3592                 op->o_bd = be;
3593                 op->o_callback = scp;
3594                 op->o_dn = dn;
3595                 op->o_ndn = ndn;
3596                 op->o_req_dn = xdn;
3597                 op->o_req_ndn = xndn;
3598         }
3599         free( odn.bv_val );
3600         free( ondn.bv_val );
3601         if ( e->e_private )
3602                 config_rename_kids( e->e_private );
3603         return rc;
3604 }
3605
3606 static int
3607 config_renumber_one( Operation *op, SlapReply *rs, CfEntryInfo *parent, 
3608         Entry *e, int idx, int tailindex, int use_ldif )
3609 {
3610         struct berval ival, newrdn, nnewrdn;
3611         struct berval rdn;
3612         Attribute *a;
3613         char ibuf[32], *ptr1, *ptr2 = NULL;
3614         int rc = 0;
3615
3616         rc = config_rename_attr( rs, e, &rdn, &a );
3617         if ( rc ) return rc;
3618
3619         ival.bv_val = ibuf;
3620         ival.bv_len = snprintf( ibuf, sizeof( ibuf ), SLAP_X_ORDERED_FMT, idx );
3621         if ( ival.bv_len >= sizeof( ibuf ) ) {
3622                 return LDAP_NAMING_VIOLATION;
3623         }
3624         
3625         newrdn.bv_len = rdn.bv_len + ival.bv_len;
3626         newrdn.bv_val = ch_malloc( newrdn.bv_len+1 );
3627
3628         if ( tailindex ) {
3629                 ptr1 = lutil_strncopy( newrdn.bv_val, rdn.bv_val, rdn.bv_len );
3630                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3631         } else {
3632                 int xlen;
3633                 ptr2 = ber_bvchr( &rdn, '}' );
3634                 if ( ptr2 ) {
3635                         ptr2++;
3636                 } else {
3637                         ptr2 = rdn.bv_val + a->a_desc->ad_cname.bv_len + 1;
3638                 }
3639                 xlen = rdn.bv_len - (ptr2 - rdn.bv_val);
3640                 ptr1 = lutil_strncopy( newrdn.bv_val, a->a_desc->ad_cname.bv_val,
3641                         a->a_desc->ad_cname.bv_len );
3642                 *ptr1++ = '=';
3643                 ptr1 = lutil_strcopy( ptr1, ival.bv_val );
3644                 ptr1 = lutil_strncopy( ptr1, ptr2, xlen );
3645                 *ptr1 = '\0';
3646         }
3647
3648         /* Do the equivalent of ModRDN */
3649         /* Replace DN / NDN */
3650         newrdn.bv_len = ptr1 - newrdn.bv_val;
3651         rdnNormalize( 0, NULL, NULL, &newrdn, &nnewrdn, NULL );
3652         rc = config_rename_one( op, rs, e, parent, a, &newrdn, &nnewrdn, use_ldif );
3653
3654         free( nnewrdn.bv_val );
3655         free( newrdn.bv_val );
3656         return rc;
3657 }
3658
3659 static int
3660 check_name_index( CfEntryInfo *parent, ConfigType ce_type, Entry *e,
3661         SlapReply *rs, int *renum, int *ibase )
3662 {
3663         CfEntryInfo *ce;
3664         int index = -1, gotindex = 0, nsibs, rc = 0;
3665         int renumber = 0, tailindex = 0, isfrontend = 0, isconfig = 0;
3666         char *ptr1, *ptr2 = NULL;
3667         struct berval rdn;
3668
3669         if ( renum ) *renum = 0;
3670
3671         /* These entries don't get indexed/renumbered */
3672         if ( ce_type == Cft_Global ) return 0;
3673         if ( ce_type == Cft_Schema && parent->ce_type == Cft_Global ) return 0;
3674
3675         if ( ce_type == Cft_Module )
3676                 tailindex = 1;
3677
3678         /* See if the rdn has an index already */
3679         dnRdn( &e->e_name, &rdn );
3680         if ( ce_type == Cft_Database ) {
3681                 if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("frontend"),
3682                                 "frontend", STRLENOF("frontend") )) 
3683                         isfrontend = 1;
3684                 else if ( !strncmp( rdn.bv_val + rdn.bv_len - STRLENOF("config"),
3685                                 "config", STRLENOF("config") )) 
3686                         isconfig = 1;
3687         }
3688         ptr1 = ber_bvchr( &e->e_name, '{' );
3689         if ( ptr1 && ptr1 - e->e_name.bv_val < rdn.bv_len ) {
3690                 char    *next;
3691                 ptr2 = strchr( ptr1, '}' );
3692                 if (!ptr2 || ptr2 - e->e_name.bv_val > rdn.bv_len)
3693                         return LDAP_NAMING_VIOLATION;
3694                 if ( ptr2-ptr1 == 1)
3695                         return LDAP_NAMING_VIOLATION;
3696                 gotindex = 1;
3697                 index = strtol( ptr1 + 1, &next, 10 );
3698                 if ( next == ptr1 + 1 || next[ 0 ] != '}' ) {
3699                         return LDAP_NAMING_VIOLATION;
3700                 }
3701                 if ( index < 0 ) {
3702                         /* Special case, we allow -1 for the frontendDB */
3703                         if ( index != -1 || !isfrontend )
3704                                 return LDAP_NAMING_VIOLATION;
3705                 }
3706                 if ( isconfig && index != 0 ){
3707                         return LDAP_NAMING_VIOLATION;
3708                 }
3709         }
3710
3711         /* count related kids */
3712         for (nsibs=0, ce=parent->ce_kids; ce; ce=ce->ce_sibs) {
3713                 if ( ce->ce_type == ce_type ) nsibs++;
3714         }
3715
3716         /* account for -1 frontend */
3717         if ( ce_type == Cft_Database )
3718                 nsibs--;
3719
3720         if ( index != nsibs ) {
3721                 if ( gotindex ) {
3722                         if ( index < nsibs ) {
3723                                 if ( tailindex ) return LDAP_NAMING_VIOLATION;
3724                                 /* Siblings need to be renumbered */
3725                                 if ( index != -1 || !isfrontend )
3726                                         renumber = 1;
3727                         }
3728                 }
3729                 /* config DB is always "0" */
3730                 if ( isconfig && index == -1 ) {
3731                         index = 0;
3732                 }
3733                 if ( !isfrontend && index == -1 ) {
3734                         index = nsibs;
3735                 }
3736
3737                 /* just make index = nsibs */
3738                 if ( !renumber ) {
3739                         rc = config_renumber_one( NULL, rs, parent, e, index, tailindex, 0 );
3740                 }
3741         }
3742         if ( ibase ) *ibase = index;
3743         if ( renum ) *renum = renumber;
3744         return rc;
3745 }
3746
3747 static int
3748 count_oc( ObjectClass *oc, ConfigOCs ***copp, int *nocs )
3749 {
3750         ConfigOCs       co, *cop;
3751         ObjectClass     **sups;
3752
3753         co.co_name = &oc->soc_cname;
3754         cop = avl_find( CfOcTree, &co, CfOc_cmp );
3755         if ( cop ) {
3756                 int     i;
3757
3758                 /* check for duplicates */
3759                 for ( i = 0; i < *nocs; i++ ) {
3760                         if ( *copp && (*copp)[i] == cop ) {
3761                                 break;
3762                         }
3763                 }
3764
3765                 if ( i == *nocs ) {
3766                         ConfigOCs **tmp = ch_realloc( *copp, (*nocs + 1)*sizeof( ConfigOCs * ) );
3767                         if ( tmp == NULL ) {
3768                                 return -1;
3769                         }
3770                         *copp = tmp;
3771                         (*copp)[*nocs] = cop;
3772                         (*nocs)++;
3773                 }
3774         }
3775
3776         for ( sups = oc->soc_sups; sups && *sups; sups++ ) {
3777                 if ( count_oc( *sups, copp, nocs ) ) {
3778                         return -1;
3779                 }
3780         }
3781
3782         return 0;
3783 }
3784
3785 static ConfigOCs **
3786 count_ocs( Attribute *oc_at, int *nocs )
3787 {
3788         int             i;
3789         ConfigOCs       **colst = NULL;
3790
3791         *nocs = 0;
3792
3793         for ( i = 0; !BER_BVISNULL( &oc_at->a_nvals[i] ); i++ )
3794                 /* count attrs */ ;
3795
3796         for ( ; i--; ) {
3797                 ObjectClass     *oc = oc_bvfind( &oc_at->a_nvals[i] );
3798
3799                 assert( oc != NULL );
3800                 if ( count_oc( oc, &colst, nocs ) ) {
3801                         ch_free( colst );
3802                         return NULL;
3803                 }
3804         }
3805
3806         return colst;
3807 }
3808
3809 static int
3810 cfAddInclude( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3811 {
3812         /* Leftover from RE23. Never parse this entry */
3813         return LDAP_COMPARE_TRUE;
3814 }
3815
3816 static int
3817 cfAddSchema( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
3818 {
3819         ConfigFile *cfo;
3820
3821         /* This entry is hardcoded, don't re-parse it */
3822         if ( p->ce_type == Cft_Global ) {
3823                 cfn = p->ce_private;
3824                 ca->private = cfn;
3825                 return LDAP_COMPARE_TRUE;
3826         }
3827         if ( p->ce_type != Cft_Schema )
3828                 return LDAP_CONSTRAINT_VIOLATION;
3829
3830         cfn = ch_calloc( 1, sizeof(ConfigFile) );
3831         ca->private = cfn;
3832         cfo = p->ce_private;
3833         cfn->c_sibs = cfo->c_kids;
3834         cfo->c_kids = cfn;
3835         return LDAP_SUCCESS;
3836 }
3837
3838 static int
3839 cfAddDatabase( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3840 {
3841         if ( p->ce_type != Cft_Global ) {
3842                 return LDAP_CONSTRAINT_VIOLATION;
3843         }
3844         ca->be = frontendDB;    /* just to get past check_vals */
3845         return LDAP_SUCCESS;
3846 }
3847
3848 static int
3849 cfAddBackend( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3850 {
3851         if ( p->ce_type != Cft_Global ) {
3852                 return LDAP_CONSTRAINT_VIOLATION;
3853         }
3854         return LDAP_SUCCESS;
3855 }
3856
3857 static int
3858 cfAddModule( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3859 {
3860         if ( p->ce_type != Cft_Global ) {
3861                 return LDAP_CONSTRAINT_VIOLATION;
3862         }
3863         return LDAP_SUCCESS;
3864 }
3865
3866 static int
3867 cfAddOverlay( CfEntryInfo *p, Entry *e, struct config_args_s *ca )
3868 {
3869         if ( p->ce_type != Cft_Database ) {
3870                 return LDAP_CONSTRAINT_VIOLATION;
3871         }
3872         ca->be = p->ce_be;
3873         return LDAP_SUCCESS;
3874 }
3875
3876 static void
3877 schema_destroy_one( ConfigArgs *ca, ConfigOCs **colst, int nocs,
3878         CfEntryInfo *p )
3879 {
3880         ConfigTable *ct;
3881         ConfigFile *cfo;
3882         AttributeDescription *ad;
3883         const char *text;
3884
3885         ca->valx = -1;
3886         ca->line = NULL;
3887         if ( cfn->c_cr_head ) {
3888                 struct berval bv = BER_BVC("olcDitContentRules");
3889                 ad = NULL;
3890                 slap_bv2ad( &bv, &ad, &text );
3891                 ct = config_find_table( colst, nocs, ad, ca );
3892                 config_del_vals( ct, ca );
3893         }
3894         if ( cfn->c_oc_head ) {
3895                 struct berval bv = BER_BVC("olcObjectClasses");
3896                 ad = NULL;
3897                 slap_bv2ad( &bv, &ad, &text );
3898                 ct = config_find_table( colst, nocs, ad, ca );
3899                 config_del_vals( ct, ca );
3900         }
3901         if ( cfn->c_at_head ) {
3902                 struct berval bv = BER_BVC("olcAttributeTypes");
3903                 ad = NULL;
3904                 slap_bv2ad( &bv, &ad, &text );
3905                 ct = config_find_table( colst, nocs, ad, ca );
3906                 config_del_vals( ct, ca );
3907         }
3908         if ( cfn->c_om_head ) {
3909                 struct berval bv = BER_BVC("olcObjectIdentifier");
3910                 ad = NULL;
3911                 slap_bv2ad( &bv, &ad, &text );
3912                 ct = config_find_table( colst, nocs, ad, ca );
3913                 config_del_vals( ct, ca );
3914         }
3915         cfo = p->ce_private;
3916         cfo->c_kids = cfn->c_sibs;
3917         ch_free( cfn );
3918 }
3919
3920 static int
3921 config_add_oc( ConfigOCs **cop, CfEntryInfo *last, Entry *e, ConfigArgs *ca )
3922 {
3923         int             rc = LDAP_CONSTRAINT_VIOLATION;
3924         ObjectClass     **ocp;
3925
3926         if ( (*cop)->co_ldadd ) {
3927                 rc = (*cop)->co_ldadd( last, e, ca );
3928                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3929                         return rc;
3930                 }
3931         }
3932
3933         for ( ocp = (*cop)->co_oc->soc_sups; ocp && *ocp; ocp++ ) {
3934                 ConfigOCs       co = { 0 };
3935
3936                 co.co_name = &(*ocp)->soc_cname;
3937                 *cop = avl_find( CfOcTree, &co, CfOc_cmp );
3938                 if ( *cop == NULL ) {
3939                         return rc;
3940                 }
3941
3942                 rc = config_add_oc( cop, last, e, ca );
3943                 if ( rc != LDAP_CONSTRAINT_VIOLATION ) {
3944                         return rc;
3945                 }
3946         }
3947
3948         return rc;
3949 }
3950
3951 /* Parse an LDAP entry into config directives */
3952 static int
3953 config_add_internal( CfBackInfo *cfb, Entry *e, ConfigArgs *ca, SlapReply *rs,
3954         int *renum, Operation *op )
3955 {
3956         CfEntryInfo     *ce, *last = NULL;
3957         ConfigOCs       co, *coptr, **colst;
3958         Attribute       *a, *oc_at, *soc_at;
3959         int             i, ibase = -1, nocs, rc = 0;
3960         struct berval   pdn;
3961         ConfigTable     *ct;
3962         char            *ptr, *log_prefix = op ? op->o_log_prefix : "";
3963
3964         memset( ca, 0, sizeof(ConfigArgs));
3965
3966         /* Make sure parent exists and entry does not. But allow
3967          * Databases and Overlays to be inserted. Don't do any
3968          * auto-renumbering if manageDSAit control is present.
3969          */
3970         ce = config_find_base( cfb->cb_root, &e->e_nname, &last );
3971         if ( ce ) {
3972                 if ( ( op && op->o_managedsait ) ||
3973                         ( ce->ce_type != Cft_Database && ce->ce_type != Cft_Overlay &&
3974                           ce->ce_type != Cft_Module ) )
3975                 {
3976                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3977                                 "DN=\"%s\" already exists\n",
3978                                 log_prefix, e->e_name.bv_val, 0 );
3979                         return LDAP_ALREADY_EXISTS;
3980                 }
3981         }
3982
3983         dnParent( &e->e_nname, &pdn );
3984
3985         /* If last is NULL, the new entry is the root/suffix entry, 
3986          * otherwise last should be the parent.
3987          */
3988         if ( last && !dn_match( &last->ce_entry->e_nname, &pdn ) ) {
3989                 if ( rs ) {
3990                         rs->sr_matched = last->ce_entry->e_name.bv_val;
3991                 }
3992                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
3993                         "DN=\"%s\" not child of DN=\"%s\"\n",
3994                         log_prefix, e->e_name.bv_val,
3995                         last->ce_entry->e_name.bv_val );
3996                 return LDAP_NO_SUCH_OBJECT;
3997         }
3998
3999         if ( op ) {
4000                 /* No parent, must be root. This will never happen... */
4001                 if ( !last && !be_isroot( op ) && !be_shadow_update( op ) ) {
4002                         return LDAP_NO_SUCH_OBJECT;
4003                 }
4004
4005                 if ( last && !access_allowed( op, last->ce_entry,
4006                         slap_schema.si_ad_children, NULL, ACL_WADD, NULL ) )
4007                 {
4008                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4009                                 "DN=\"%s\" no write access to \"children\" of parent\n",
4010                                 log_prefix, e->e_name.bv_val, 0 );
4011                         return LDAP_INSUFFICIENT_ACCESS;
4012                 }
4013         }
4014
4015         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
4016         if ( !oc_at ) {
4017                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4018                         "DN=\"%s\" no objectClass\n",
4019                         log_prefix, e->e_name.bv_val, 0 );
4020                 return LDAP_OBJECT_CLASS_VIOLATION;
4021         }
4022
4023         soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4024         if ( !soc_at ) {
4025                 ObjectClass     *soc = NULL;
4026                 char            textbuf[ SLAP_TEXT_BUFLEN ];
4027                 const char      *text = textbuf;
4028
4029                 /* FIXME: check result */
4030                 rc = structural_class( oc_at->a_nvals, &soc, NULL,
4031                         &text, textbuf, sizeof(textbuf), NULL );
4032                 if ( rc != LDAP_SUCCESS ) {
4033                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4034                                 "DN=\"%s\" no structural objectClass (%s)\n",
4035                                 log_prefix, e->e_name.bv_val, text );
4036                         return rc;
4037                 }
4038                 attr_merge_one( e, slap_schema.si_ad_structuralObjectClass, &soc->soc_cname, NULL );
4039                 soc_at = attr_find( e->e_attrs, slap_schema.si_ad_structuralObjectClass );
4040                 if ( soc_at == NULL ) {
4041                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4042                                 "DN=\"%s\" no structural objectClass; "
4043                                 "unable to merge computed class %s\n",
4044                                 log_prefix, e->e_name.bv_val,
4045                                 soc->soc_cname.bv_val );
4046                         return LDAP_OBJECT_CLASS_VIOLATION;
4047                 }
4048
4049                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4050                         "DN=\"%s\" no structural objectClass; "
4051                         "computed objectClass %s merged\n",
4052                         log_prefix, e->e_name.bv_val,
4053                         soc->soc_cname.bv_val );
4054         }
4055
4056         /* Fake the coordinates based on whether we're part of an
4057          * LDAP Add or if reading the config dir
4058          */
4059         if ( rs ) {
4060                 ca->fname = "slapd";
4061                 ca->lineno = 0;
4062         } else {
4063                 ca->fname = cfdir.bv_val;
4064                 ca->lineno = 1;
4065         }
4066         ca->ca_op = op;
4067
4068         co.co_name = &soc_at->a_nvals[0];
4069         coptr = avl_find( CfOcTree, &co, CfOc_cmp );
4070         if ( coptr == NULL ) {
4071                 Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4072                         "DN=\"%s\" no structural objectClass in configuration table\n",
4073                         log_prefix, e->e_name.bv_val, 0 );
4074                 return LDAP_OBJECT_CLASS_VIOLATION;
4075         }
4076
4077         /* Only the root can be Cft_Global, everything else must
4078          * have a parent. Only limited nesting arrangements are allowed.
4079          */
4080         rc = LDAP_CONSTRAINT_VIOLATION;
4081         if ( coptr->co_type == Cft_Global && !last ) {
4082                 cfn = cfb->cb_config;
4083                 ca->private = cfn;
4084                 ca->be = frontendDB;    /* just to get past check_vals */
4085                 rc = LDAP_SUCCESS;
4086         }
4087
4088         /* Check whether the Add is allowed by its parent, and do
4089          * any necessary arg setup
4090          */
4091         if ( last ) {
4092                 rc = config_add_oc( &coptr, last, e, ca );
4093                 if ( rc == LDAP_CONSTRAINT_VIOLATION ) {
4094                         Debug( LDAP_DEBUG_TRACE, "%s: config_add_internal: "
4095                                 "DN=\"%s\" no structural objectClass add function\n",
4096                                 log_prefix, e->e_name.bv_val, 0 );
4097                         return LDAP_OBJECT_CLASS_VIOLATION;
4098                 }
4099         }
4100
4101         colst = count_ocs( oc_at, &nocs );
4102
4103         /* Add the entry but don't parse it, we already have its contents */
4104         if ( rc == LDAP_COMPARE_TRUE ) {
4105                 rc = LDAP_SUCCESS;
4106                 goto ok;
4107         }
4108
4109         if ( rc != LDAP_SUCCESS )
4110                 goto done_noop;
4111
4112         /* Parse all the values and check for simple syntax errors before
4113          * performing any set actions.
4114          *
4115          * If doing an LDAPadd, check for indexed names and any necessary
4116          * renaming/renumbering. Entries that don't need indexed names are
4117          * ignored. Entries that need an indexed name and arrive without one
4118          * are assigned to the end. Entries that arrive with an index may
4119          * cause the following entries to be renumbered/bumped down.
4120          *
4121          * Note that "pseudo-indexed" entries (cn=Include{xx}, cn=Module{xx})
4122          * don't allow Adding an entry with an index that's already in use.
4123          * This is flagged as an error (LDAP_ALREADY_EXISTS) up above.
4124          *
4125          * These entries can have auto-assigned indexes (appended to the end)
4126          * but only the other types support auto-renumbering of siblings.
4127          */
4128         {
4129                 rc = check_name_index( last, coptr->co_type, e, rs, renum,
4130                         &ibase );
4131                 if ( rc ) {
4132                         goto done_noop;
4133                 }
4134                 if ( renum && *renum && coptr->co_type != Cft_Database &&
4135                         coptr->co_type != Cft_Overlay )
4136                 {
4137                         snprintf( ca->cr_msg, sizeof( ca->cr_msg ),
4138                                 "operation requires sibling renumbering" );
4139                         rc = LDAP_UNWILLING_TO_PERFORM;
4140                         goto done_noop;
4141                 }
4142         }
4143
4144         init_config_argv( ca );
4145
4146         /* Make sure we process attrs in the required order */
4147         sort_attrs( e, colst, nocs );
4148
4149         for ( a = e->e_attrs; a; a = a->a_next ) {
4150                 if ( a == oc_at ) continue;
4151                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4152                 if ( !ct ) continue;    /* user data? */
4153                 rc = check_vals( ct, ca, a, 1 );
4154                 if ( rc ) goto done_noop;
4155         }
4156
4157         /* Basic syntax checks are OK. Do the actual settings. */
4158         for ( a=e->e_attrs; a; a=a->a_next ) {
4159                 if ( a == oc_at ) continue;
4160                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4161                 if ( !ct ) continue;    /* user data? */
4162                 for (i=0; a->a_vals[i].bv_val; i++) {
4163                         char *iptr = NULL;
4164                         ca->line = a->a_vals[i].bv_val;
4165                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED ) {
4166                                 ptr = strchr( ca->line, '}' );
4167                                 if ( ptr ) {
4168                                         iptr = strchr( ca->line, '{' );
4169                                         ca->line = ptr+1;
4170                                 }
4171                         }
4172                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED_SIB ) {
4173                                 if ( iptr ) {
4174                                         ca->valx = strtol( iptr+1, NULL, 0 );
4175                                 } else {
4176                                         ca->valx = -1;
4177                                 }
4178                         } else {
4179                                 ca->valx = i;
4180                         }
4181                         rc = config_parse_add( ct, ca, i );
4182                         if ( rc ) {
4183                                 rc = LDAP_OTHER;
4184                                 goto done;
4185                         }
4186                 }
4187         }
4188 ok:
4189         /* Newly added databases and overlays need to be started up */
4190         if ( CONFIG_ONLINE_ADD( ca )) {
4191                 if ( colst[0]->co_type == Cft_Database ) {
4192                         rc = backend_startup_one( ca->be, &ca->reply );
4193
4194                 } else if ( colst[0]->co_type == Cft_Overlay ) {
4195                         if ( ca->bi->bi_db_open ) {
4196                                 BackendInfo *bi_orig = ca->be->bd_info;
4197                                 ca->be->bd_info = ca->bi;
4198                                 rc = ca->bi->bi_db_open( ca->be, &ca->reply );
4199                                 ca->be->bd_info = bi_orig;
4200                         }
4201                 }
4202                 if ( rc ) {
4203                         if (ca->cr_msg[0] == '\0')
4204                                 snprintf( ca->cr_msg, sizeof( ca->cr_msg ), "<%s> failed startup", ca->argv[0] );
4205
4206                         Debug(LDAP_DEBUG_ANY, "%s: %s (%s)!\n",
4207                                 ca->log, ca->cr_msg, ca->argv[1] );
4208                         rc = LDAP_OTHER;
4209                         goto done;
4210                 }
4211         }
4212
4213         ca->valx = ibase;
4214         ce = ch_calloc( 1, sizeof(CfEntryInfo) );
4215         ce->ce_parent = last;
4216         ce->ce_entry = entry_dup( e );
4217         ce->ce_entry->e_private = ce;
4218         ce->ce_type = colst[0]->co_type;
4219         ce->ce_be = ca->be;
4220         ce->ce_bi = ca->bi;
4221         ce->ce_private = ca->private;
4222         ca->ca_entry = ce->ce_entry;
4223         if ( !last ) {
4224                 cfb->cb_root = ce;
4225         } else if ( last->ce_kids ) {
4226                 CfEntryInfo *c2, **cprev;
4227
4228                 /* Advance to first of this type */
4229                 cprev = &last->ce_kids;
4230                 for ( c2 = *cprev; c2 && c2->ce_type < ce->ce_type; ) {
4231                         cprev = &c2->ce_sibs;
4232                         c2 = c2->ce_sibs;
4233                 }
4234                 /* Account for the (-1) frontendDB entry */
4235                 if ( ce->ce_type == Cft_Database ) {
4236                         if ( ca->be == frontendDB )
4237                                 ibase = 0;
4238                         else if ( ibase != -1 )
4239                                 ibase++;
4240                 }
4241                 /* Append */
4242                 if ( ibase < 0 ) {
4243                         for (c2 = *cprev; c2 && c2->ce_type == ce->ce_type;) {
4244                                 cprev = &c2->ce_sibs;
4245                                 c2 = c2->ce_sibs;
4246                         }
4247                 } else {
4248                 /* Insert */
4249                         int i;
4250                         for ( i=0; i<ibase; i++ ) {
4251                                 c2 = *cprev;
4252                                 cprev = &c2->ce_sibs;
4253                         }
4254                 }
4255                 ce->ce_sibs = *cprev;
4256                 *cprev = ce;
4257         } else {
4258                 last->ce_kids = ce;
4259         }
4260
4261 done:
4262         if ( rc ) {
4263                 if ( (colst[0]->co_type == Cft_Database) && ca->be ) {
4264                         if ( ca->be != frontendDB )
4265                                 backend_destroy_one( ca->be, 1 );
4266                 } else if ( (colst[0]->co_type == Cft_Overlay) && ca->bi ) {
4267                         overlay_destroy_one( ca->be, (slap_overinst *)ca->bi );
4268                 } else if ( colst[0]->co_type == Cft_Schema ) {
4269                         schema_destroy_one( ca, colst, nocs, last );
4270                 }
4271         }
4272 done_noop:
4273
4274         ch_free( ca->argv );
4275         if ( colst ) ch_free( colst );
4276         return rc;
4277 }
4278
4279 #define BIGTMP  10000
4280 static int
4281 config_rename_add( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4282         int base, int rebase, int max, int use_ldif )
4283 {
4284         CfEntryInfo *ce2, *ce3, *cetmp = NULL, *cerem = NULL;
4285         ConfigType etype = ce->ce_type;
4286         int count = 0, rc = 0;
4287
4288         /* Reverse ce list */
4289         for (ce2 = ce->ce_sibs;ce2;ce2 = ce3) {
4290                 if (ce2->ce_type != etype) {
4291                         cerem = ce2;
4292                         break;
4293                 }
4294                 ce3 = ce2->ce_sibs;
4295                 ce2->ce_sibs = cetmp;
4296                 cetmp = ce2;
4297                 count++;
4298                 if ( max && count >= max ) {
4299                         cerem = ce3;
4300                         break;
4301                 }
4302         }
4303
4304         /* Move original to a temp name until increments are done */
4305         if ( rebase ) {
4306                 ce->ce_entry->e_private = NULL;
4307                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4308                         base+BIGTMP, 0, use_ldif );
4309                 ce->ce_entry->e_private = ce;
4310         }
4311         /* start incrementing */
4312         for (ce2=cetmp; ce2; ce2=ce3) {
4313                 ce3 = ce2->ce_sibs;
4314                 ce2->ce_sibs = cerem;
4315                 cerem = ce2;
4316                 if ( rc == 0 ) 
4317                         rc = config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4318                                 count+base, 0, use_ldif );
4319                 count--;
4320         }
4321         if ( rebase )
4322                 rc = config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4323                         base, 0, use_ldif );
4324         return rc;
4325 }
4326
4327 static int
4328 config_rename_del( Operation *op, SlapReply *rs, CfEntryInfo *ce,
4329         CfEntryInfo *ce2, int old, int use_ldif )
4330 {
4331         int count = 0;
4332
4333         /* Renumber original to a temp value */
4334         ce->ce_entry->e_private = NULL;
4335         config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4336                 old+BIGTMP, 0, use_ldif );
4337         ce->ce_entry->e_private = ce;
4338
4339         /* start decrementing */
4340         for (; ce2 != ce; ce2=ce2->ce_sibs) {
4341                 config_renumber_one( op, rs, ce2->ce_parent, ce2->ce_entry,
4342                         count+old, 0, use_ldif );
4343                 count++;
4344         }
4345         return config_renumber_one( op, rs, ce->ce_parent, ce->ce_entry,
4346                 count+old, 0, use_ldif );
4347 }
4348
4349 /* Parse an LDAP entry into config directives, then store in underlying
4350  * database.
4351  */
4352 static int
4353 config_back_add( Operation *op, SlapReply *rs )
4354 {
4355         CfBackInfo *cfb;
4356         int renumber;
4357         ConfigArgs ca;
4358
4359         if ( !access_allowed( op, op->ora_e, slap_schema.si_ad_entry,
4360                 NULL, ACL_WADD, NULL )) {
4361                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4362                 goto out;
4363         }
4364
4365         cfb = (CfBackInfo *)op->o_bd->be_private;
4366
4367         /* add opattrs for syncprov */
4368         {
4369                 char textbuf[SLAP_TEXT_BUFLEN];
4370                 size_t textlen = sizeof textbuf;
4371                 rs->sr_err = entry_schema_check(op, op->ora_e, NULL, 0, 1,
4372                         &rs->sr_text, textbuf, sizeof( textbuf ) );
4373                 if ( rs->sr_err != LDAP_SUCCESS )
4374                         goto out;
4375                 rs->sr_err = slap_add_opattrs( op, &rs->sr_text, textbuf, textlen, 1 );
4376                 if ( rs->sr_err != LDAP_SUCCESS ) {
4377                         Debug( LDAP_DEBUG_TRACE,
4378                                 LDAP_XSTRING(config_back_add) ": entry failed op attrs add: "
4379                                 "%s (%d)\n", rs->sr_text, rs->sr_err, 0 );
4380                         goto out;
4381                 }
4382         }
4383
4384         ldap_pvt_thread_pool_pause( &connection_pool );
4385
4386         /* Strategy:
4387          * 1) check for existence of entry
4388          * 2) check for sibling renumbering
4389          * 3) perform internal add
4390          * 4) perform any necessary renumbering
4391          * 5) store entry in underlying database
4392          */
4393         rs->sr_err = config_add_internal( cfb, op->ora_e, &ca, rs, &renumber, op );
4394         if ( rs->sr_err != LDAP_SUCCESS ) {
4395                 rs->sr_text = ca.cr_msg;
4396                 goto out2;
4397         }
4398
4399         if ( renumber ) {
4400                 CfEntryInfo *ce = ca.ca_entry->e_private;
4401                 req_add_s addr = op->oq_add;
4402                 op->o_tag = LDAP_REQ_MODRDN;
4403                 rs->sr_err = config_rename_add( op, rs, ce, ca.valx, 0, 0, cfb->cb_use_ldif );
4404                 op->o_tag = LDAP_REQ_ADD;
4405                 op->oq_add = addr;
4406                 if ( rs->sr_err != LDAP_SUCCESS ) {
4407                         goto out2;
4408                 }
4409         }
4410
4411         if ( cfb->cb_use_ldif ) {
4412                 BackendDB *be = op->o_bd;
4413                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4414                 struct berval dn, ndn;
4415
4416                 op->o_bd = &cfb->cb_db;
4417
4418                 /* Save current rootdn; use the underlying DB's rootdn */
4419                 dn = op->o_dn;
4420                 ndn = op->o_ndn;
4421                 op->o_dn = op->o_bd->be_rootdn;
4422                 op->o_ndn = op->o_bd->be_rootndn;
4423
4424                 scp = op->o_callback;
4425                 op->o_callback = &sc;
4426                 op->o_bd->be_add( op, rs );
4427                 op->o_bd = be;
4428                 op->o_callback = scp;
4429                 op->o_dn = dn;
4430                 op->o_ndn = ndn;
4431         }
4432
4433 out2:;
4434         ldap_pvt_thread_pool_resume( &connection_pool );
4435
4436 out:;
4437         send_ldap_result( op, rs );
4438         slap_graduate_commit_csn( op );
4439         return rs->sr_err;
4440 }
4441
4442 typedef struct delrec {
4443         struct delrec *next;
4444         int nidx;
4445         int idx[1];
4446 } delrec;
4447
4448 static int
4449 config_modify_add( ConfigTable *ct, ConfigArgs *ca, AttributeDescription *ad,
4450         int i )
4451 {
4452         int rc;
4453
4454         if (ad->ad_type->sat_flags & SLAP_AT_ORDERED &&
4455                 ca->line[0] == '{' )
4456         {
4457                 char *ptr = strchr( ca->line + 1, '}' );
4458                 if ( ptr ) {
4459                         char    *next;
4460
4461                         ca->valx = strtol( ca->line + 1, &next, 0 );
4462                         if ( next == ca->line + 1 || next[ 0 ] != '}' ) {
4463                                 return LDAP_OTHER;
4464                         }
4465                         ca->line = ptr+1;
4466                 }
4467         }
4468         rc = config_parse_add( ct, ca, i );
4469         if ( rc ) {
4470                 rc = LDAP_OTHER;
4471         }
4472         return rc;
4473 }
4474
4475 static int
4476 config_modify_internal( CfEntryInfo *ce, Operation *op, SlapReply *rs,
4477         ConfigArgs *ca )
4478 {
4479         int rc = LDAP_UNWILLING_TO_PERFORM;
4480         Modifications *ml;
4481         Entry *e = ce->ce_entry;
4482         Attribute *save_attrs = e->e_attrs, *oc_at, *s, *a;
4483         ConfigTable *ct;
4484         ConfigOCs **colst;
4485         int i, nocs;
4486         char *ptr;
4487         delrec *dels = NULL, *deltail = NULL;
4488
4489         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
4490         if ( !oc_at ) return LDAP_OBJECT_CLASS_VIOLATION;
4491
4492         colst = count_ocs( oc_at, &nocs );
4493
4494         /* make sure add/del flags are clear; should always be true */
4495         for ( s = save_attrs; s; s = s->a_next ) {
4496                 s->a_flags &= ~(SLAP_ATTR_IXADD|SLAP_ATTR_IXDEL);
4497         }
4498
4499         e->e_attrs = attrs_dup( e->e_attrs );
4500
4501         init_config_argv( ca );
4502         ca->be = ce->ce_be;
4503         ca->bi = ce->ce_bi;
4504         ca->private = ce->ce_private;
4505         ca->ca_entry = e;
4506         ca->fname = "slapd";
4507         ca->ca_op = op;
4508         strcpy( ca->log, "back-config" );
4509
4510         for (ml = op->orm_modlist; ml; ml=ml->sml_next) {
4511                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4512                 switch (ml->sml_op) {
4513                 case LDAP_MOD_DELETE:
4514                 case LDAP_MOD_REPLACE: {
4515                         BerVarray vals = NULL, nvals = NULL;
4516                         int *idx = NULL;
4517                         if ( ct && ( ct->arg_type & ARG_NO_DELETE )) {
4518                                 rc = LDAP_OTHER;
4519                                 snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot delete %s",
4520                                         ml->sml_desc->ad_cname.bv_val );
4521                                 goto out_noop;
4522                         }
4523                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4524                                 vals = ml->sml_values;
4525                                 nvals = ml->sml_nvalues;
4526                                 ml->sml_values = NULL;
4527                                 ml->sml_nvalues = NULL;
4528                         }
4529                         /* If we're deleting by values, remember the indexes of the
4530                          * values we deleted.
4531                          */
4532                         if ( ct && ml->sml_values ) {
4533                                 delrec *d;
4534                                 for (i=0; ml->sml_values[i].bv_val; i++);
4535                                 d = ch_malloc( sizeof(delrec) + (i - 1)* sizeof(int));
4536                                 d->nidx = i;
4537                                 d->next = NULL;
4538                                 if ( dels ) {
4539                                         deltail->next = d;
4540                                 } else {
4541                                         dels = d;
4542                                 }
4543                                 deltail = d;
4544                                 idx = d->idx;
4545                         }
4546                         rc = modify_delete_vindex(e, &ml->sml_mod,
4547                                 get_permissiveModify(op),
4548                                 &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg), idx );
4549                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4550                                 ml->sml_values = vals;
4551                                 ml->sml_nvalues = nvals;
4552                         }
4553                         if ( !vals )
4554                                 break;
4555                         }
4556                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4557
4558                 case LDAP_MOD_ADD:
4559                 case SLAP_MOD_SOFTADD: {
4560                         int mop = ml->sml_op;
4561                         int navals = -1;
4562                         ml->sml_op = LDAP_MOD_ADD;
4563                         if ( ct ) {
4564                                 if ( ct->arg_type & ARG_NO_INSERT ) {
4565                                         Attribute *a = attr_find( e->e_attrs, ml->sml_desc );
4566                                         if ( a ) {
4567                                                 for (i = 0; a->a_vals[i].bv_val; i++ );
4568                                                 navals = i;
4569                                         }
4570                                 }
4571                                 for ( i=0; !BER_BVISNULL( &ml->sml_values[i] ); i++ ) {
4572                                         if ( ml->sml_values[i].bv_val[0] == '{' &&
4573                                                 navals >= 0 )
4574                                         {
4575                                                 char    *next, *val = ml->sml_values[i].bv_val + 1;
4576                                                 int     j;
4577
4578                                                 j = strtol( val, &next, 0 );
4579                                                 if ( next == val || next[ 0 ] != '}' || j < navals ) {
4580                                                         rc = LDAP_OTHER;
4581                                                         snprintf(ca->cr_msg, sizeof(ca->cr_msg), "cannot insert %s",
4582                                                                 ml->sml_desc->ad_cname.bv_val );
4583                                                         goto out_noop;
4584                                                 }
4585                                         }
4586                                         rc = check_vals( ct, ca, ml, 0 );
4587                                         if ( rc ) goto out_noop;
4588                                 }
4589                         }
4590                         rc = modify_add_values(e, &ml->sml_mod,
4591                                    get_permissiveModify(op),
4592                                    &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4593
4594                         /* If value already exists, show success here
4595                          * and ignore this operation down below.
4596                          */
4597                         if ( mop == SLAP_MOD_SOFTADD ) {
4598                                 if ( rc == LDAP_TYPE_OR_VALUE_EXISTS )
4599                                         rc = LDAP_SUCCESS;
4600                                 else
4601                                         mop = LDAP_MOD_ADD;
4602                         }
4603                         ml->sml_op = mop;
4604                         break;
4605                         }
4606
4607                         break;
4608                 case LDAP_MOD_INCREMENT:        /* FIXME */
4609                         break;
4610                 default:
4611                         break;
4612                 }
4613                 if(rc != LDAP_SUCCESS) break;
4614         }
4615         
4616         if ( rc == LDAP_SUCCESS) {
4617                 /* check that the entry still obeys the schema */
4618                 rc = entry_schema_check(op, e, NULL, 0, 0,
4619                         &rs->sr_text, ca->cr_msg, sizeof(ca->cr_msg) );
4620                 if ( rc ) goto out_noop;
4621         }
4622         /* Basic syntax checks are OK. Do the actual settings. */
4623         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4624                 ct = config_find_table( colst, nocs, ml->sml_desc, ca );
4625                 if ( !ct ) continue;
4626
4627                 s = attr_find( save_attrs, ml->sml_desc );
4628                 a = attr_find( e->e_attrs, ml->sml_desc );
4629
4630                 switch (ml->sml_op) {
4631                 case LDAP_MOD_DELETE:
4632                 case LDAP_MOD_REPLACE: {
4633                         BerVarray vals = NULL, nvals = NULL;
4634                         delrec *d = NULL;
4635
4636                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4637                                 vals = ml->sml_values;
4638                                 nvals = ml->sml_nvalues;
4639                                 ml->sml_values = NULL;
4640                                 ml->sml_nvalues = NULL;
4641                         }
4642
4643                         if ( ml->sml_values )
4644                                 d = dels;
4645
4646                         /* If we didn't delete the whole attribute */
4647                         if ( ml->sml_values && a ) {
4648                                 struct berval *mvals;
4649                                 int j;
4650
4651                                 if ( ml->sml_nvalues )
4652                                         mvals = ml->sml_nvalues;
4653                                 else
4654                                         mvals = ml->sml_values;
4655
4656                                 /* use the indexes we saved up above */
4657                                 for (i=0; i < d->nidx; i++) {
4658                                         struct berval bv = *mvals++;
4659                                         if ( a->a_desc->ad_type->sat_flags & SLAP_AT_ORDERED &&
4660                                                 bv.bv_val[0] == '{' ) {
4661                                                 ptr = strchr( bv.bv_val, '}' ) + 1;
4662                                                 bv.bv_len -= ptr - bv.bv_val;
4663                                                 bv.bv_val = ptr;
4664                                         }
4665                                         ca->line = bv.bv_val;
4666                                         ca->valx = d->idx[i];
4667                                         rc = config_del_vals( ct, ca );
4668                                         if ( rc != LDAP_SUCCESS ) break;
4669                                         if ( s )
4670                                                 s->a_flags |= SLAP_ATTR_IXDEL;
4671                                         for (j=i+1; j < d->nidx; j++)
4672                                                 if ( d->idx[j] >d->idx[i] )
4673                                                         d->idx[j]--;
4674                                 }
4675                         } else {
4676                                 ca->valx = -1;
4677                                 ca->line = NULL;
4678                                 rc = config_del_vals( ct, ca );
4679                                 if ( rc ) rc = LDAP_OTHER;
4680                                 if ( s )
4681                                         s->a_flags |= SLAP_ATTR_IXDEL;
4682                         }
4683                         if ( ml->sml_values ) {
4684                                 d = d->next;
4685                                 ch_free( dels );
4686                                 dels = d;
4687                         }
4688                         if ( ml->sml_op == LDAP_MOD_REPLACE ) {
4689                                 ml->sml_values = vals;
4690                                 ml->sml_nvalues = nvals;
4691                         }
4692                         if ( !vals || rc != LDAP_SUCCESS )
4693                                 break;
4694                         }
4695                         /* FALLTHRU: LDAP_MOD_REPLACE && vals */
4696
4697                 case LDAP_MOD_ADD:
4698                         for (i=0; ml->sml_values[i].bv_val; i++) {
4699                                 ca->line = ml->sml_values[i].bv_val;
4700                                 ca->valx = -1;
4701                                 rc = config_modify_add( ct, ca, ml->sml_desc, i );
4702                                 if ( rc )
4703                                         goto out;
4704                                 a->a_flags |= SLAP_ATTR_IXADD;
4705                         }
4706                         break;
4707                 }
4708         }
4709
4710 out:
4711         /* Undo for a failed operation */
4712         if ( rc != LDAP_SUCCESS ) {
4713                 for ( s = save_attrs; s; s = s->a_next ) {
4714                         if ( s->a_flags & SLAP_ATTR_IXDEL ) {
4715                                 s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4716                                 ct = config_find_table( colst, nocs, s->a_desc, ca );
4717                                 a = attr_find( e->e_attrs, s->a_desc );
4718                                 if ( a ) {
4719                                         /* clear the flag so the add check below will skip it */
4720                                         a->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4721                                         ca->valx = -1;
4722                                         ca->line = NULL;
4723                                         config_del_vals( ct, ca );
4724                                 }
4725                                 for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4726                                         ca->line = s->a_vals[i].bv_val;
4727                                         ca->valx = -1;
4728                                         config_modify_add( ct, ca, s->a_desc, i );
4729                                 }
4730                         }
4731                 }
4732                 for ( a = e->e_attrs; a; a = a->a_next ) {
4733                         if ( a->a_flags & SLAP_ATTR_IXADD ) {
4734                                 ct = config_find_table( colst, nocs, a->a_desc, ca );
4735                                 ca->valx = -1;
4736                                 ca->line = NULL;
4737                                 config_del_vals( ct, ca );
4738                                 s = attr_find( save_attrs, a->a_desc );
4739                                 if ( s ) {
4740                                         s->a_flags &= ~(SLAP_ATTR_IXDEL|SLAP_ATTR_IXADD);
4741                                         for ( i=0; !BER_BVISNULL( &s->a_vals[i] ); i++ ) {
4742                                                 ca->line = s->a_vals[i].bv_val;
4743                                                 ca->valx = -1;
4744                                                 config_modify_add( ct, ca, s->a_desc, i );
4745                                         }
4746                                 }
4747                         }
4748                 }
4749         }
4750
4751         if ( ca->cleanup )
4752                 ca->cleanup( ca );
4753 out_noop:
4754         if ( rc == LDAP_SUCCESS ) {
4755                 attrs_free( save_attrs );
4756         } else {
4757                 attrs_free( e->e_attrs );
4758                 e->e_attrs = save_attrs;
4759         }
4760         ch_free( ca->argv );
4761         if ( colst ) ch_free( colst );
4762         while( dels ) {
4763                 deltail = dels->next;
4764                 ch_free( dels );
4765                 dels = deltail;
4766         }
4767
4768         return rc;
4769 }
4770
4771 static int
4772 config_back_modify( Operation *op, SlapReply *rs )
4773 {
4774         CfBackInfo *cfb;
4775         CfEntryInfo *ce, *last;
4776         Modifications *ml;
4777         ConfigArgs ca = {0};
4778         struct berval rdn;
4779         char *ptr;
4780         AttributeDescription *rad = NULL;
4781
4782         cfb = (CfBackInfo *)op->o_bd->be_private;
4783
4784         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4785         if ( !ce ) {
4786                 if ( last )
4787                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4788                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4789                 goto out;
4790         }
4791
4792         if ( !acl_check_modlist( op, ce->ce_entry, op->orm_modlist )) {
4793                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4794                 goto out;
4795         }
4796
4797         /* Get type of RDN */
4798         rdn = ce->ce_entry->e_nname;
4799         ptr = strchr( rdn.bv_val, '=' );
4800         rdn.bv_len = ptr - rdn.bv_val;
4801         slap_bv2ad( &rdn, &rad, &rs->sr_text );
4802
4803         /* Some basic validation... */
4804         for ( ml = op->orm_modlist; ml; ml = ml->sml_next ) {
4805                 /* Don't allow Modify of RDN; must use ModRdn for that. */
4806                 if ( ml->sml_desc == rad ) {
4807                         rs->sr_err = LDAP_NOT_ALLOWED_ON_RDN;
4808                         rs->sr_text = "Use modrdn to change the entry name";
4809                         goto out;
4810                 }
4811         }
4812
4813         slap_mods_opattrs( op, &op->orm_modlist, 1 );
4814
4815         if ( !slapd_shutdown )
4816                 ldap_pvt_thread_pool_pause( &connection_pool );
4817
4818         /* Strategy:
4819          * 1) perform the Modify on the cached Entry.
4820          * 2) verify that the Entry still satisfies the schema.
4821          * 3) perform the individual config operations.
4822          * 4) store Modified entry in underlying LDIF backend.
4823          */
4824         rs->sr_err = config_modify_internal( ce, op, rs, &ca );
4825         if ( rs->sr_err ) {
4826                 rs->sr_text = ca.cr_msg;
4827         } else if ( cfb->cb_use_ldif ) {
4828                 BackendDB *be = op->o_bd;
4829                 slap_callback sc = { NULL, slap_null_cb, NULL, NULL }, *scp;
4830                 struct berval dn, ndn;
4831
4832                 op->o_bd = &cfb->cb_db;
4833
4834                 dn = op->o_dn;
4835                 ndn = op->o_ndn;
4836                 op->o_dn = op->o_bd->be_rootdn;
4837                 op->o_ndn = op->o_bd->be_rootndn;
4838
4839                 scp = op->o_callback;
4840                 op->o_callback = &sc;
4841                 op->o_bd->be_modify( op, rs );
4842                 op->o_bd = be;
4843                 op->o_callback = scp;
4844                 op->o_dn = dn;
4845                 op->o_ndn = ndn;
4846         }
4847
4848         if ( !slapd_shutdown )
4849                 ldap_pvt_thread_pool_resume( &connection_pool );
4850 out:
4851         send_ldap_result( op, rs );
4852         slap_graduate_commit_csn( op );
4853         return rs->sr_err;
4854 }
4855
4856 static int
4857 config_back_modrdn( Operation *op, SlapReply *rs )
4858 {
4859         CfBackInfo *cfb;
4860         CfEntryInfo *ce, *last;
4861         struct berval rdn;
4862         int ixold, ixnew;
4863
4864         cfb = (CfBackInfo *)op->o_bd->be_private;
4865
4866         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
4867         if ( !ce ) {
4868                 if ( last )
4869                         rs->sr_matched = last->ce_entry->e_name.bv_val;
4870                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
4871                 goto out;
4872         }
4873         if ( !access_allowed( op, ce->ce_entry, slap_schema.si_ad_entry,
4874                 NULL, ACL_WRITE, NULL )) {
4875                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4876                 goto out;
4877         }
4878         { Entry *parent;
4879                 if ( ce->ce_parent )
4880                         parent = ce->ce_parent->ce_entry;
4881                 else
4882                         parent = (Entry *)&slap_entry_root;
4883                 if ( !access_allowed( op, parent, slap_schema.si_ad_children,
4884                         NULL, ACL_WRITE, NULL )) {
4885                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
4886                         goto out;
4887                 }
4888         }
4889
4890         /* We don't allow moving objects to new parents.
4891          * Generally we only allow reordering a set of ordered entries.
4892          */
4893         if ( op->orr_newSup ) {
4894                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4895                 goto out;
4896         }
4897
4898         /* If newRDN == oldRDN, quietly succeed */
4899         dnRdn( &op->o_req_ndn, &rdn );
4900         if ( dn_match( &rdn, &op->orr_nnewrdn )) {
4901                 rs->sr_err = LDAP_SUCCESS;
4902                 goto out;
4903         }
4904
4905         /* Current behavior, subject to change as needed:
4906          *
4907          * For backends and overlays, we only allow renumbering.
4908          * For schema, we allow renaming with the same number.
4909          * Otherwise, the op is not allowed.
4910          */
4911
4912         if ( ce->ce_type == Cft_Schema ) {
4913                 char *ptr1, *ptr2;
4914                 int len;
4915
4916                 /* Can't alter the main cn=schema entry */
4917                 if ( ce->ce_parent->ce_type == Cft_Global ) {
4918                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4919                         rs->sr_text = "renaming not allowed for this entry";
4920                         goto out;
4921                 }
4922
4923                 /* We could support this later if desired */
4924                 ptr1 = ber_bvchr( &rdn, '}' );
4925                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4926                 len = ptr1 - rdn.bv_val;
4927                 if ( len != ptr2 - op->orr_newrdn.bv_val ||
4928                         strncmp( rdn.bv_val, op->orr_newrdn.bv_val, len )) {
4929                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4930                         rs->sr_text = "schema reordering not supported";
4931                         goto out;
4932                 }
4933         } else if ( ce->ce_type == Cft_Database ||
4934                 ce->ce_type == Cft_Overlay ) {
4935                 char *ptr1, *ptr2, *iptr1, *iptr2;
4936                 int len1, len2;
4937
4938                 iptr2 = ber_bvchr( &op->orr_newrdn, '=' ) + 1;
4939                 if ( *iptr2 != '{' ) {
4940                         rs->sr_err = LDAP_NAMING_VIOLATION;
4941                         rs->sr_text = "new ordering index is required";
4942                         goto out;
4943                 }
4944                 iptr2++;
4945                 iptr1 = ber_bvchr( &rdn, '{' ) + 1;
4946                 ptr1 = ber_bvchr( &rdn, '}' );
4947                 ptr2 = ber_bvchr( &op->orr_newrdn, '}' );
4948                 if ( !ptr2 ) {
4949                         rs->sr_err = LDAP_NAMING_VIOLATION;
4950                         rs->sr_text = "new ordering index is required";
4951                         goto out;
4952                 }
4953
4954                 len1 = ptr1 - rdn.bv_val;
4955                 len2 = ptr2 - op->orr_newrdn.bv_val;
4956
4957                 if ( rdn.bv_len - len1 != op->orr_newrdn.bv_len - len2 ||
4958                         strncmp( ptr1, ptr2, rdn.bv_len - len1 )) {
4959                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4960                         rs->sr_text = "changing database/overlay type not allowed";
4961                         goto out;
4962                 }
4963                 ixold = strtol( iptr1, NULL, 0 );
4964                 ixnew = strtol( iptr2, &ptr1, 0 );
4965                 if ( ptr1 != ptr2 || ixold < 0 || ixnew < 0 ) {
4966                         rs->sr_err = LDAP_NAMING_VIOLATION;
4967                         goto out;
4968                 }
4969                 /* config DB is always 0, cannot be changed */
4970                 if ( ce->ce_type == Cft_Database && ( ixold == 0 || ixnew == 0 )) {
4971                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
4972                         goto out;
4973                 }
4974         } else {
4975                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
4976                 rs->sr_text = "renaming not supported for this entry";
4977                 goto out;
4978         }
4979
4980         ldap_pvt_thread_pool_pause( &connection_pool );
4981
4982         if ( ce->ce_type == Cft_Schema ) {
4983                 req_modrdn_s modr = op->oq_modrdn;
4984                 struct berval rdn;
4985                 Attribute *a;
4986                 rs->sr_err = config_rename_attr( rs, ce->ce_entry, &rdn, &a );
4987                 if ( rs->sr_err == LDAP_SUCCESS ) {
4988                         rs->sr_err = config_rename_one( op, rs, ce->ce_entry,
4989                                 ce->ce_parent, a, &op->orr_newrdn, &op->orr_nnewrdn,
4990                                 cfb->cb_use_ldif );
4991                 }
4992                 op->oq_modrdn = modr;
4993         } else {
4994                 CfEntryInfo *ce2, *cebase, **cprev, **cbprev, *ceold;
4995                 req_modrdn_s modr = op->oq_modrdn;
4996                 int i;
4997
4998                 /* Advance to first of this type */
4999                 cprev = &ce->ce_parent->ce_kids;
5000                 for ( ce2 = *cprev; ce2 && ce2->ce_type != ce->ce_type; ) {
5001                         cprev = &ce2->ce_sibs;
5002                         ce2 = ce2->ce_sibs;
5003                 }
5004                 /* Skip the -1 entry */
5005                 if ( ce->ce_type == Cft_Database ) {
5006                         cprev = &ce2->ce_sibs;
5007                         ce2 = ce2->ce_sibs;
5008                 }
5009                 cebase = ce2;
5010                 cbprev = cprev;
5011
5012                 /* Remove from old slot */
5013                 for ( ce2 = *cprev; ce2 && ce2 != ce; ce2 = ce2->ce_sibs )
5014                         cprev = &ce2->ce_sibs;
5015                 *cprev = ce->ce_sibs;
5016                 ceold = ce->ce_sibs;
5017
5018                 /* Insert into new slot */
5019                 cprev = cbprev;
5020                 for ( i=0; i<ixnew; i++ ) {
5021                         ce2 = *cprev;
5022                         if ( !ce2 )
5023                                 break;
5024                         cprev = &ce2->ce_sibs;
5025                 }
5026                 ce->ce_sibs = *cprev;
5027                 *cprev = ce;
5028
5029                 ixnew = i;
5030
5031                 /* NOTE: These should be encoded in the OC tables, not inline here */
5032                 if ( ce->ce_type == Cft_Database )
5033                         backend_db_move( ce->ce_be, ixnew );
5034                 else if ( ce->ce_type == Cft_Overlay )
5035                         overlay_move( ce->ce_be, (slap_overinst *)ce->ce_bi, ixnew );
5036                         
5037                 if ( ixold < ixnew ) {
5038                         rs->sr_err = config_rename_del( op, rs, ce, ceold, ixold,
5039                                 cfb->cb_use_ldif );
5040                 } else {
5041                         rs->sr_err = config_rename_add( op, rs, ce, ixnew, 1,
5042                                 ixold - ixnew, cfb->cb_use_ldif );
5043                 }
5044                 op->oq_modrdn = modr;
5045         }
5046
5047         ldap_pvt_thread_pool_resume( &connection_pool );
5048 out:
5049         send_ldap_result( op, rs );
5050         return rs->sr_err;
5051 }
5052
5053 static int
5054 config_back_delete( Operation *op, SlapReply *rs )
5055 {
5056         send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, NULL );
5057         return rs->sr_err;
5058 }
5059
5060 static int
5061 config_back_search( Operation *op, SlapReply *rs )
5062 {
5063         CfBackInfo *cfb;
5064         CfEntryInfo *ce, *last;
5065         slap_mask_t mask;
5066
5067         cfb = (CfBackInfo *)op->o_bd->be_private;
5068
5069         ce = config_find_base( cfb->cb_root, &op->o_req_ndn, &last );
5070         if ( !ce ) {
5071                 if ( last )
5072                         rs->sr_matched = last->ce_entry->e_name.bv_val;
5073                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
5074                 goto out;
5075         }
5076         if ( !access_allowed_mask( op, ce->ce_entry, slap_schema.si_ad_entry, NULL,
5077                 ACL_SEARCH, NULL, &mask ))
5078         {
5079                 if ( !ACL_GRANT( mask, ACL_DISCLOSE )) {
5080                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
5081                 } else {
5082                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
5083                 }
5084                 goto out;
5085         }
5086         switch ( op->ors_scope ) {
5087         case LDAP_SCOPE_BASE:
5088         case LDAP_SCOPE_SUBTREE:
5089                 config_send( op, rs, ce, 0 );
5090                 break;
5091                 
5092         case LDAP_SCOPE_ONELEVEL:
5093                 for (ce = ce->ce_kids; ce; ce=ce->ce_sibs) {
5094                         config_send( op, rs, ce, 1 );
5095                 }
5096                 break;
5097         }
5098                 
5099         rs->sr_err = LDAP_SUCCESS;
5100 out:
5101         send_ldap_result( op, rs );
5102         return 0;
5103 }
5104
5105 /* no-op, we never free entries */
5106 int config_entry_release(
5107         Operation *op,
5108         Entry *e,
5109         int rw )
5110 {
5111         if ( !e->e_private ) {
5112                 entry_free( e );
5113         }
5114         return LDAP_SUCCESS;
5115 }
5116
5117 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
5118  */
5119 int config_back_entry_get(
5120         Operation *op,
5121         struct berval *ndn,
5122         ObjectClass *oc,
5123         AttributeDescription *at,
5124         int rw,
5125         Entry **ent )
5126 {
5127         CfBackInfo *cfb;
5128         CfEntryInfo *ce, *last;
5129
5130         cfb = (CfBackInfo *)op->o_bd->be_private;
5131
5132         ce = config_find_base( cfb->cb_root, ndn, &last );
5133         if ( ce ) {
5134                 *ent = ce->ce_entry;
5135                 if ( *ent && oc && !is_entry_objectclass_or_sub( *ent, oc ) ) {
5136                         *ent = NULL;
5137                 }
5138         }
5139
5140         return ( *ent == NULL ? 1 : 0 );
5141 }
5142
5143 static void
5144 config_build_attrs( Entry *e, AttributeType **at, AttributeDescription *ad,
5145         ConfigTable *ct, ConfigArgs *c )
5146 {
5147         int i, rc;
5148
5149         for (; at && *at; at++) {
5150                 /* Skip the naming attr */
5151                 if ((*at)->sat_ad == ad || (*at)->sat_ad == slap_schema.si_ad_cn )
5152                         continue;
5153                 for (i=0;ct[i].name;i++) {
5154                         if (ct[i].ad == (*at)->sat_ad) {
5155                                 rc = config_get_vals(&ct[i], c);
5156                                 /* NOTE: tolerate that config_get_vals()
5157                                  * returns success with no values */
5158                                 if (rc == LDAP_SUCCESS && c->rvalue_vals != NULL ) {
5159                                         if ( c->rvalue_nvals )
5160                                                 attr_merge(e, ct[i].ad, c->rvalue_vals,
5161                                                         c->rvalue_nvals);
5162                                         else
5163                                                 attr_merge_normalize(e, ct[i].ad,
5164                                                         c->rvalue_vals, NULL);
5165                                         ber_bvarray_free( c->rvalue_nvals );
5166                                         ber_bvarray_free( c->rvalue_vals );
5167                                 }
5168                                 break;
5169                         }
5170                 }
5171         }
5172 }
5173
5174 Entry *
5175 config_build_entry( Operation *op, SlapReply *rs, CfEntryInfo *parent,
5176         ConfigArgs *c, struct berval *rdn, ConfigOCs *main, ConfigOCs *extra )
5177 {
5178         Entry *e = entry_alloc();
5179         CfEntryInfo *ce = ch_calloc( 1, sizeof(CfEntryInfo) );
5180         struct berval val;
5181         struct berval ad_name;
5182         AttributeDescription *ad = NULL;
5183         int rc;
5184         char *ptr;
5185         const char *text;
5186         Attribute *oc_at;
5187         struct berval pdn;
5188         ObjectClass *oc;
5189         CfEntryInfo *ceprev = NULL;
5190
5191         Debug( LDAP_DEBUG_TRACE, "config_build_entry: \"%s\"\n", rdn->bv_val, 0, 0);
5192         e->e_private = ce;
5193         ce->ce_entry = e;
5194         ce->ce_type = main->co_type;
5195         ce->ce_parent = parent;
5196         if ( parent ) {
5197                 pdn = parent->ce_entry->e_nname;
5198                 if ( parent->ce_kids )
5199                         for ( ceprev = parent->ce_kids; ceprev->ce_sibs &&
5200                                 ceprev->ce_type <= ce->ce_type;
5201                                 ceprev = ceprev->ce_sibs );
5202         } else {
5203                 BER_BVZERO( &pdn );
5204         }
5205
5206         ce->ce_private = c->private;
5207         ce->ce_be = c->be;
5208         ce->ce_bi = c->bi;
5209
5210         build_new_dn( &e->e_name, &pdn, rdn, NULL );
5211         ber_dupbv( &e->e_nname, &e->e_name );
5212
5213         attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5214                 main->co_name, NULL );
5215         if ( extra )
5216                 attr_merge_normalize_one(e, slap_schema.si_ad_objectClass,
5217                         extra->co_name, NULL );
5218         ptr = strchr(rdn->bv_val, '=');
5219         ad_name.bv_val = rdn->bv_val;
5220         ad_name.bv_len = ptr - rdn->bv_val;
5221         rc = slap_bv2ad( &ad_name, &ad, &text );
5222         if ( rc ) {
5223                 return NULL;
5224         }
5225         val.bv_val = ptr+1;
5226         val.bv_len = rdn->bv_len - (val.bv_val - rdn->bv_val);
5227         attr_merge_normalize_one(e, ad, &val, NULL );
5228
5229         oc = main->co_oc;
5230         c->table = main->co_type;
5231         if ( oc->soc_required )
5232                 config_build_attrs( e, oc->soc_required, ad, main->co_table, c );
5233
5234         if ( oc->soc_allowed )
5235                 config_build_attrs( e, oc->soc_allowed, ad, main->co_table, c );
5236
5237         if ( extra ) {
5238                 oc = extra->co_oc;
5239                 c->table = extra->co_type;
5240                 if ( oc->soc_required )
5241                         config_build_attrs( e, oc->soc_required, ad, extra->co_table, c );
5242
5243                 if ( oc->soc_allowed )
5244                         config_build_attrs( e, oc->soc_allowed, ad, extra->co_table, c );
5245         }
5246
5247         oc_at = attr_find( e->e_attrs, slap_schema.si_ad_objectClass );
5248         rc = structural_class(oc_at->a_vals, &oc, NULL, &text, c->cr_msg,
5249                 sizeof(c->cr_msg), op ? op->o_tmpmemctx : NULL );
5250         attr_merge_normalize_one(e, slap_schema.si_ad_structuralObjectClass, &oc->soc_cname, NULL );
5251         if ( op && !op->o_noop ) {
5252                 op->ora_e = e;
5253                 op->ora_modlist = NULL;
5254                 op->o_bd->be_add( op, rs );
5255                 if ( ( rs->sr_err != LDAP_SUCCESS ) 
5256                                 && (rs->sr_err != LDAP_ALREADY_EXISTS) ) {
5257                         return NULL;
5258                 }
5259         }
5260         if ( ceprev ) {
5261                 ce->ce_sibs = ceprev->ce_sibs;
5262                 ceprev->ce_sibs = ce;
5263         } else if ( parent ) {
5264                 ce->ce_sibs = parent->ce_kids;
5265                 parent->ce_kids = ce;
5266         }
5267
5268         return e;
5269 }
5270
5271 static int
5272 config_build_schema_inc( ConfigArgs *c, CfEntryInfo *ceparent,
5273         Operation *op, SlapReply *rs )
5274 {
5275         Entry *e;
5276         ConfigFile *cf = c->private;
5277         char *ptr;
5278         struct berval bv;
5279
5280         for (; cf; cf=cf->c_sibs, c->depth++) {
5281                 if ( !cf->c_at_head && !cf->c_cr_head && !cf->c_oc_head &&
5282                         !cf->c_om_head ) continue;
5283                 c->value_dn.bv_val = c->log;
5284                 LUTIL_SLASHPATH( cf->c_file.bv_val );
5285                 bv.bv_val = strrchr(cf->c_file.bv_val, LDAP_DIRSEP[0]);
5286                 if ( !bv.bv_val ) {
5287                         bv = cf->c_file;
5288                 } else {
5289                         bv.bv_val++;
5290                         bv.bv_len = cf->c_file.bv_len - (bv.bv_val - cf->c_file.bv_val);
5291                 }
5292                 ptr = strchr( bv.bv_val, '.' );
5293                 if ( ptr )
5294                         bv.bv_len = ptr - bv.bv_val;
5295                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=" SLAP_X_ORDERED_FMT, c->depth);
5296                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5297                         /* FIXME: how can indicate error? */
5298                         return -1;
5299                 }
5300                 strncpy( c->value_dn.bv_val + c->value_dn.bv_len, bv.bv_val,
5301                         bv.bv_len );
5302                 c->value_dn.bv_len += bv.bv_len;
5303                 c->value_dn.bv_val[c->value_dn.bv_len] ='\0';
5304
5305                 c->private = cf;
5306                 e = config_build_entry( op, rs, ceparent, c, &c->value_dn,
5307                         &CFOC_SCHEMA, NULL );
5308                 if ( !e ) {
5309                         return -1;
5310                 } else if ( e && cf->c_kids ) {
5311                         c->private = cf->c_kids;
5312                         config_build_schema_inc( c, e->e_private, op, rs );
5313                 }
5314         }
5315         return 0;
5316 }
5317
5318 #ifdef SLAPD_MODULES
5319
5320 static int
5321 config_build_modules( ConfigArgs *c, CfEntryInfo *ceparent,
5322         Operation *op, SlapReply *rs )
5323 {
5324         int i;
5325         ModPaths *mp;
5326
5327         for (i=0, mp=&modpaths; mp; mp=mp->mp_next, i++) {
5328                 if ( BER_BVISNULL( &mp->mp_path ) && !mp->mp_loads )
5329                         continue;
5330                 c->value_dn.bv_val = c->log;
5331                 c->value_dn.bv_len = snprintf(c->value_dn.bv_val, sizeof( c->log ), "cn=module" SLAP_X_ORDERED_FMT, i);
5332                 if ( c->value_dn.bv_len >= sizeof( c->log ) ) {
5333                         /* FIXME: how can indicate error? */
5334                         return -1;
5335                 }
5336                 c->private = mp;
5337                 if ( ! config_build_entry( op, rs, ceparent, c, &c->value_dn, &CFOC_MODULE, NULL )) {
5338                         return -1;
5339                 }
5340         }
5341         return 0;
5342 }
5343 #endif
5344
5345 static int
5346 config_check_schema(Operation *op, CfBackInfo *cfb)
5347 {
5348         struct berval schema_dn = BER_BVC(SCHEMA_RDN "," CONFIG_RDN);
5349         ConfigArgs c = {0};
5350         CfEntryInfo *ce, *last;
5351         Entry *e;
5352
5353         /* If there's no root entry, we must be in the midst of converting */
5354         if ( !cfb->cb_root )
5355                 return 0;
5356
5357         /* Make sure the main schema entry exists */
5358         ce = config_find_base( cfb->cb_root, &schema_dn, &last );
5359         if ( ce ) {
5360                 Attribute *a;
5361                 struct berval *bv;
5362
5363                 e = ce->ce_entry;
5364
5365                 /* Make sure it's up to date */
5366                 if ( cf_om_tail != om_sys_tail ) {
5367                         a = attr_find( e->e_attrs, cfAd_om );
5368                         if ( a ) {
5369                                 if ( a->a_nvals != a->a_vals )
5370                                         ber_bvarray_free( a->a_nvals );
5371                                 ber_bvarray_free( a->a_vals );
5372                                 a->a_vals = NULL;
5373                                 a->a_nvals = NULL;
5374                         }
5375                         oidm_unparse( &bv, NULL, NULL, 1 );
5376                         attr_merge_normalize( e, cfAd_om, bv, NULL );
5377                         ber_bvarray_free( bv );
5378                         cf_om_tail = om_sys_tail;
5379                 }
5380                 if ( cf_at_tail != at_sys_tail ) {
5381                         a = attr_find( e->e_attrs, cfAd_attr );
5382                         if ( a ) {
5383                                 if ( a->a_nvals != a->a_vals )
5384                                         ber_bvarray_free( a->a_nvals );
5385                                 ber_bvarray_free( a->a_vals );
5386                                 a->a_vals = NULL;
5387                                 a->a_nvals = NULL;
5388                         }
5389                         at_unparse( &bv, NULL, NULL, 1 );
5390                         attr_merge_normalize( e, cfAd_attr, bv, NULL );
5391                         ber_bvarray_free( bv );
5392                         cf_at_tail = at_sys_tail;
5393                 }
5394                 if ( cf_oc_tail != oc_sys_tail ) {
5395                         a = attr_find( e->e_attrs, cfAd_oc );
5396                         if ( a ) {
5397                                 if ( a->a_nvals != a->a_vals )
5398                                         ber_bvarray_free( a->a_nvals );
5399                                 ber_bvarray_free( a->a_vals );
5400                                 a->a_vals = NULL;
5401                                 a->a_nvals = NULL;
5402                         }
5403                         oc_unparse( &bv, NULL, NULL, 1 );
5404                         attr_merge_normalize( e, cfAd_oc, bv, NULL );
5405                         ber_bvarray_free( bv );
5406                         cf_oc_tail = oc_sys_tail;
5407                 }
5408         } else {
5409                 SlapReply rs = {REP_RESULT};
5410                 c.private = NULL;
5411                 e = config_build_entry( op, &rs, cfb->cb_root, &c, &schema_rdn,
5412                         &CFOC_SCHEMA, NULL );
5413                 if ( !e ) {
5414                         return -1;
5415                 }
5416                 ce = e->e_private;
5417                 ce->ce_private = cfb->cb_config;
5418                 cf_at_tail = at_sys_tail;
5419                 cf_oc_tail = oc_sys_tail;
5420                 cf_om_tail = om_sys_tail;
5421         }
5422         return 0;
5423 }
5424
5425 static const char *defacl[] = {
5426         NULL, "to", "*", "by", "*", "none", NULL
5427 };
5428
5429 static int
5430 config_back_db_open( BackendDB *be, ConfigReply *cr )
5431 {
5432         CfBackInfo *cfb = be->be_private;
5433         struct berval rdn;
5434         Entry *e, *parent;
5435         CfEntryInfo *ce, *ceparent;
5436         int i, unsupp = 0;
5437         BackendInfo *bi;
5438         ConfigArgs c;
5439         Connection conn = {0};
5440         OperationBuffer opbuf;
5441         Operation *op;
5442         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
5443         SlapReply rs = {REP_RESULT};
5444         void *thrctx = NULL;
5445
5446         Debug( LDAP_DEBUG_TRACE, "config_back_db_open\n", 0, 0, 0);
5447
5448         /* If we have no explicitly configured ACLs, don't just use
5449          * the global ACLs. Explicitly deny access to everything.
5450          */
5451         if ( frontendDB->be_acl && be->be_acl == frontendDB->be_acl ) {
5452                 parse_acl(be, "config_back_db_open", 0, 6, (char **)defacl, 0 );
5453         }
5454
5455         thrctx = ldap_pvt_thread_pool_context();
5456         connection_fake_init( &conn, &opbuf, thrctx );
5457         op = &opbuf.ob_op;
5458
5459         op->o_tag = LDAP_REQ_ADD;
5460         op->o_callback = &cb;
5461         op->o_bd = &cfb->cb_db;
5462         op->o_dn = op->o_bd->be_rootdn;
5463         op->o_ndn = op->o_bd->be_rootndn;
5464
5465         if ( !cfb->cb_use_ldif ) {
5466                 op->o_noop = 1;
5467         }
5468
5469         /* If we read the config from back-ldif, do some quick sanity checks */
5470         if ( cfb->cb_got_ldif ) {
5471                 return config_check_schema( op, cfb );
5472         }
5473
5474         /* create root of tree */
5475         rdn = config_rdn;
5476         c.private = cfb->cb_config;
5477         c.be = frontendDB;
5478         e = config_build_entry( op, &rs, NULL, &c, &rdn, &CFOC_GLOBAL, NULL );
5479         if ( !e ) {
5480                 return -1;
5481         }
5482         ce = e->e_private;
5483         cfb->cb_root = ce;
5484
5485         parent = e;
5486         ceparent = ce;
5487
5488 #ifdef SLAPD_MODULES
5489         /* Create Module nodes... */
5490         if ( modpaths.mp_loads ) {
5491                 if ( config_build_modules( &c, ceparent, op, &rs ) ){
5492                         return -1;
5493                 }
5494         }
5495 #endif
5496
5497         /* Create schema nodes... cn=schema will contain the hardcoded core
5498          * schema, read-only. Child objects will contain runtime loaded schema
5499          * files.
5500          */
5501         rdn = schema_rdn;
5502         c.private = NULL;
5503         e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_SCHEMA, NULL );
5504         if ( !e ) {
5505                 return -1;
5506         }
5507         ce = e->e_private;
5508         ce->ce_private = cfb->cb_config;
5509         cf_at_tail = at_sys_tail;
5510         cf_oc_tail = oc_sys_tail;
5511         cf_om_tail = om_sys_tail;
5512
5513         /* Create schema nodes for included schema... */
5514         if ( cfb->cb_config->c_kids ) {
5515                 c.depth = 0;
5516                 c.private = cfb->cb_config->c_kids;
5517                 if (config_build_schema_inc( &c, ce, op, &rs )) {
5518                         return -1;
5519                 }
5520         }
5521
5522         /* Create backend nodes. Skip if they don't provide a cf_table.
5523          * There usually aren't any of these.
5524          */
5525         
5526         c.line = 0;
5527         LDAP_STAILQ_FOREACH( bi, &backendInfo, bi_next) {
5528                 if (!bi->bi_cf_ocs) {
5529                         /* If it only supports the old config mech, complain. */
5530                         if ( bi->bi_config ) {
5531                                 Debug( LDAP_DEBUG_ANY,
5532                                         "WARNING: No dynamic config support for backend %s.\n",
5533                                         bi->bi_type, 0, 0 );
5534                                 unsupp++;
5535                         }
5536                         continue;
5537                 }
5538                 if (!bi->bi_private) continue;
5539
5540                 rdn.bv_val = c.log;
5541                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5542                         "%s=%s", cfAd_backend->ad_cname.bv_val, bi->bi_type);
5543                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5544                         /* FIXME: holler ... */ ;
5545                 }
5546                 c.bi = bi;
5547                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_BACKEND,
5548                         bi->bi_cf_ocs );
5549                 if ( !e ) {
5550                         return -1;
5551                 }
5552         }
5553
5554         /* Create database nodes... */
5555         frontendDB->be_cf_ocs = &CFOC_FRONTEND;
5556         LDAP_STAILQ_NEXT(frontendDB, be_next) = LDAP_STAILQ_FIRST(&backendDB);
5557         for ( i = -1, be = frontendDB ; be;
5558                 i++, be = LDAP_STAILQ_NEXT( be, be_next )) {
5559                 slap_overinfo *oi = NULL;
5560
5561                 if ( overlay_is_over( be )) {
5562                         oi = be->bd_info->bi_private;
5563                         bi = oi->oi_orig;
5564                 } else {
5565                         bi = be->bd_info;
5566                 }
5567
5568                 /* If this backend supports the old config mechanism, but not
5569                  * the new mech, complain.
5570                  */
5571                 if ( !be->be_cf_ocs && bi->bi_db_config ) {
5572                         Debug( LDAP_DEBUG_ANY,
5573                                 "WARNING: No dynamic config support for database %s.\n",
5574                                 bi->bi_type, 0, 0 );
5575                         unsupp++;
5576                 }
5577                 rdn.bv_val = c.log;
5578                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5579                         "%s=" SLAP_X_ORDERED_FMT "%s", cfAd_database->ad_cname.bv_val,
5580                         i, bi->bi_type);
5581                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5582                         /* FIXME: holler ... */ ;
5583                 }
5584                 c.be = be;
5585                 c.bi = bi;
5586                 e = config_build_entry( op, &rs, ceparent, &c, &rdn, &CFOC_DATABASE,
5587                         be->be_cf_ocs );
5588                 if ( !e ) {
5589                         return -1;
5590                 }
5591                 ce = e->e_private;
5592                 if ( be->be_cf_ocs && be->be_cf_ocs->co_cfadd )
5593                         be->be_cf_ocs->co_cfadd( op, &rs, e, &c );
5594                 /* Iterate through overlays */
5595                 if ( oi ) {
5596                         slap_overinst *on;
5597                         Entry *oe;
5598                         int j;
5599
5600                         for (j=0,on=oi->oi_list; on; j++,on=on->on_next) {
5601                                 if ( on->on_bi.bi_db_config && !on->on_bi.bi_cf_ocs ) {
5602                                         Debug( LDAP_DEBUG_ANY,
5603                                                 "WARNING: No dynamic config support for overlay %s.\n",
5604                                                 on->on_bi.bi_type, 0, 0 );
5605                                         unsupp++;
5606                                 }
5607                                 rdn.bv_val = c.log;
5608                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( c.log ),
5609                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5610                                         cfAd_overlay->ad_cname.bv_val, j, on->on_bi.bi_type );
5611                                 if ( rdn.bv_len >= sizeof( c.log ) ) {
5612                                         /* FIXME: holler ... */ ;
5613                                 }
5614                                 c.be = be;
5615                                 c.bi = &on->on_bi;
5616                                 oe = config_build_entry( op, &rs, ce, &c, &rdn,
5617                                         &CFOC_OVERLAY, c.bi->bi_cf_ocs );
5618                                 if ( !oe ) {
5619                                         return -1;
5620                                 }
5621                                 if ( c.bi->bi_cf_ocs && c.bi->bi_cf_ocs->co_cfadd )
5622                                         c.bi->bi_cf_ocs->co_cfadd( op, &rs, oe, &c );
5623                         }
5624                 }
5625         }
5626         if ( thrctx )
5627                 ldap_pvt_thread_pool_context_reset( thrctx );
5628
5629         if ( unsupp  && cfb->cb_use_ldif ) {
5630                 Debug( LDAP_DEBUG_ANY, "\nWARNING: The converted cn=config "
5631                         "directory is incomplete and may not work.\n\n", 0, 0, 0 );
5632         }
5633
5634         return 0;
5635 }
5636
5637 static void
5638 cfb_free_cffile( ConfigFile *cf )
5639 {
5640         ConfigFile *next;
5641
5642         for (; cf; cf=next) {
5643                 next = cf->c_sibs;
5644                 if ( cf->c_kids )
5645                         cfb_free_cffile( cf->c_kids );
5646                 ch_free( cf->c_file.bv_val );
5647                 ber_bvarray_free( cf->c_dseFiles );
5648                 ch_free( cf );
5649         }
5650 }
5651
5652 static void
5653 cfb_free_entries( CfEntryInfo *ce )
5654 {
5655         CfEntryInfo *next;
5656
5657         for (; ce; ce=next) {
5658                 next = ce->ce_sibs;
5659                 if ( ce->ce_kids )
5660                         cfb_free_entries( ce->ce_kids );
5661                 ce->ce_entry->e_private = NULL;
5662                 entry_free( ce->ce_entry );
5663                 ch_free( ce );
5664         }
5665 }
5666
5667 static int
5668 config_back_db_close( BackendDB *be, ConfigReply *cr )
5669 {
5670         CfBackInfo *cfb = be->be_private;
5671
5672         cfb_free_entries( cfb->cb_root );
5673         cfb->cb_root = NULL;
5674
5675         if ( cfb->cb_db.bd_info ) {
5676                 backend_shutdown( &cfb->cb_db );
5677         }
5678
5679         return 0;
5680 }
5681
5682 static int
5683 config_back_db_destroy( BackendDB *be, ConfigReply *cr )
5684 {
5685         CfBackInfo *cfb = be->be_private;
5686
5687         cfb_free_cffile( cfb->cb_config );
5688
5689         ch_free( cfdir.bv_val );
5690
5691         avl_free( CfOcTree, NULL );
5692
5693         if ( cfb->cb_db.bd_info ) {
5694                 cfb->cb_db.be_suffix = NULL;
5695                 cfb->cb_db.be_nsuffix = NULL;
5696                 BER_BVZERO( &cfb->cb_db.be_rootdn );
5697                 BER_BVZERO( &cfb->cb_db.be_rootndn );
5698
5699                 backend_destroy_one( &cfb->cb_db, 0 );
5700         }
5701
5702         loglevel_destroy();
5703
5704         return 0;
5705 }
5706
5707 static int
5708 config_back_db_init( BackendDB *be, ConfigReply* cr )
5709 {
5710         struct berval dn;
5711         CfBackInfo *cfb;
5712
5713         cfb = &cfBackInfo;
5714         cfb->cb_config = ch_calloc( 1, sizeof(ConfigFile));
5715         cfn = cfb->cb_config;
5716         be->be_private = cfb;
5717
5718         ber_dupbv( &be->be_rootdn, &config_rdn );
5719         ber_dupbv( &be->be_rootndn, &be->be_rootdn );
5720         ber_dupbv( &dn, &be->be_rootdn );
5721         ber_bvarray_add( &be->be_suffix, &dn );
5722         ber_dupbv( &dn, &be->be_rootdn );
5723         ber_bvarray_add( &be->be_nsuffix, &dn );
5724
5725         /* Hide from namingContexts */
5726         SLAP_BFLAGS(be) |= SLAP_BFLAG_CONFIG;
5727
5728         return 0;
5729 }
5730
5731 static int
5732 config_back_destroy( BackendInfo *bi )
5733 {
5734         ldif_must_b64_encode_release();
5735         return 0;
5736 }
5737
5738 static int
5739 config_tool_entry_open( BackendDB *be, int mode )
5740 {
5741         CfBackInfo *cfb = be->be_private;
5742         BackendInfo *bi = cfb->cb_db.bd_info;
5743
5744         if ( bi && bi->bi_tool_entry_open )
5745                 return bi->bi_tool_entry_open( &cfb->cb_db, mode );
5746         else
5747                 return -1;
5748         
5749 }
5750
5751 static int
5752 config_tool_entry_close( BackendDB *be )
5753 {
5754         CfBackInfo *cfb = be->be_private;
5755         BackendInfo *bi = cfb->cb_db.bd_info;
5756
5757         if ( bi && bi->bi_tool_entry_close )
5758                 return bi->bi_tool_entry_close( &cfb->cb_db );
5759         else
5760                 return -1;
5761 }
5762
5763 static ID
5764 config_tool_entry_first( BackendDB *be )
5765 {
5766         CfBackInfo *cfb = be->be_private;
5767         BackendInfo *bi = cfb->cb_db.bd_info;
5768
5769         if ( bi && bi->bi_tool_entry_first )
5770                 return bi->bi_tool_entry_first( &cfb->cb_db );
5771         else
5772                 return NOID;
5773 }
5774
5775 static ID
5776 config_tool_entry_next( BackendDB *be )
5777 {
5778         CfBackInfo *cfb = be->be_private;
5779         BackendInfo *bi = cfb->cb_db.bd_info;
5780
5781         if ( bi && bi->bi_tool_entry_next )
5782                 return bi->bi_tool_entry_next( &cfb->cb_db );
5783         else
5784                 return NOID;
5785 }
5786
5787 static Entry *
5788 config_tool_entry_get( BackendDB *be, ID id )
5789 {
5790         CfBackInfo *cfb = be->be_private;
5791         BackendInfo *bi = cfb->cb_db.bd_info;
5792
5793         if ( bi && bi->bi_tool_entry_get )
5794                 return bi->bi_tool_entry_get( &cfb->cb_db, id );
5795         else
5796                 return NULL;
5797 }
5798
5799 static int entry_put_got_frontend=0;
5800 static int entry_put_got_config=0;
5801 static ID
5802 config_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
5803 {
5804         CfBackInfo *cfb = be->be_private;
5805         BackendInfo *bi = cfb->cb_db.bd_info;
5806         int rc;
5807         struct berval rdn, vals[ 2 ];
5808         ConfigArgs ca;
5809         OperationBuffer opbuf;
5810         Entry *ce;
5811         Connection conn = {0};
5812         Operation *op = NULL;
5813         void *thrctx;
5814
5815         /* Create entry for frontend database if it does not exist already */
5816         if ( !entry_put_got_frontend ) {
5817                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase", 
5818                                 STRLENOF( "olcDatabase" ))) {
5819                         if ( strncmp( e->e_nname.bv_val + 
5820                                         STRLENOF( "olcDatabase" ), "={-1}frontend",
5821                                         STRLENOF( "={-1}frontend" )) && 
5822                                         strncmp( e->e_nname.bv_val + 
5823                                         STRLENOF( "olcDatabase" ), "=frontend",
5824                                         STRLENOF( "=frontend" ))) {
5825                                 vals[1].bv_len = 0;
5826                                 vals[1].bv_val = NULL;
5827                                 memset( &ca, 0, sizeof(ConfigArgs));
5828                                 ca.be = frontendDB;
5829                                 ca.bi = frontendDB->bd_info;
5830                                 ca.be->be_cf_ocs = &CFOC_FRONTEND;
5831                                 rdn.bv_val = ca.log;
5832                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5833                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5834                                         cfAd_database->ad_cname.bv_val, -1,
5835                                         ca.bi->bi_type);
5836                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn,
5837                                                 &CFOC_DATABASE, ca.be->be_cf_ocs );
5838                                 thrctx = ldap_pvt_thread_pool_context();
5839                                 connection_fake_init2( &conn, &opbuf, thrctx,0 );
5840                                 op = &opbuf.ob_op;
5841                                 op->o_bd = &cfb->cb_db;
5842                                 op->o_tag = LDAP_REQ_ADD;
5843                                 op->ora_e = ce;
5844                                 op->o_dn = be->be_rootdn;
5845                                 op->o_ndn = be->be_rootndn;
5846                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5847                                 if ( rc != LDAP_SUCCESS ) {
5848                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5849                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5850                                         return NOID;
5851                                 }
5852
5853                                 if ( ce && bi && bi->bi_tool_entry_put && 
5854                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5855                                         entry_put_got_frontend++;
5856                                 } else {
5857                                         text->bv_val = "autocreation of \"olcDatabase={-1}frontend\" failed";
5858                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={-1}frontend\" failed");
5859                                         return NOID;
5860                                 }
5861                         } else {
5862                                 entry_put_got_frontend++;
5863                         }
5864                 }
5865         }
5866         /* Create entry for config database if it does not exist already */
5867         if ( !entry_put_got_config ) {
5868                 if ( !strncmp( e->e_nname.bv_val, "olcDatabase",
5869                                 STRLENOF( "olcDatabase" ))) {
5870                         if ( strncmp( e->e_nname.bv_val +
5871                                         STRLENOF( "olcDatabase" ), "={0}config",
5872                                         STRLENOF( "={0}config" )) &&
5873                                         strncmp( e->e_nname.bv_val +
5874                                         STRLENOF( "olcDatabase" ), "=config",
5875                                         STRLENOF( "=config" )) ) {
5876                                 vals[1].bv_len = 0;
5877                                 vals[1].bv_val = NULL;
5878                                 memset( &ca, 0, sizeof(ConfigArgs));
5879                                 ca.be = LDAP_STAILQ_FIRST( &backendDB );
5880                                 ca.bi = ca.be->bd_info;
5881                                 rdn.bv_val = ca.log;
5882                                 rdn.bv_len = snprintf(rdn.bv_val, sizeof( ca.log ),
5883                                         "%s=" SLAP_X_ORDERED_FMT "%s",
5884                                         cfAd_database->ad_cname.bv_val, 0,
5885                                         ca.bi->bi_type);
5886                                 ce = config_build_entry( NULL, NULL, cfb->cb_root, &ca, &rdn, &CFOC_DATABASE,
5887                                                 ca.be->be_cf_ocs );
5888                                 if ( ! op ) {
5889                                         thrctx = ldap_pvt_thread_pool_context();
5890                                         connection_fake_init2( &conn, &opbuf, thrctx,0 );
5891                                         op = &opbuf.ob_op;
5892                                         op->o_bd = &cfb->cb_db;
5893                                         op->o_tag = LDAP_REQ_ADD;
5894                                         op->o_dn = be->be_rootdn;
5895                                         op->o_ndn = be->be_rootndn;
5896                                 }
5897                                 op->ora_e = ce;
5898                                 rc = slap_add_opattrs(op, NULL, NULL, 0, 0);
5899                                 if ( rc != LDAP_SUCCESS ) {
5900                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5901                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5902                                         return NOID;
5903                                 }
5904                                 if (ce && bi && bi->bi_tool_entry_put &&
5905                                                 bi->bi_tool_entry_put( &cfb->cb_db, ce, text ) != NOID ) {
5906                                         entry_put_got_config++;
5907                                 } else {
5908                                         text->bv_val = "autocreation of \"olcDatabase={0}config\" failed";
5909                                         text->bv_len = STRLENOF("autocreation of \"olcDatabase={0}config\" failed");
5910                                         return NOID;
5911                                 }
5912                         } else {
5913                                 entry_put_got_config++;
5914                         }
5915                 }
5916         }
5917         if ( bi && bi->bi_tool_entry_put &&
5918                 config_add_internal( cfb, e, &ca, NULL, NULL, NULL ) == 0 )
5919                 return bi->bi_tool_entry_put( &cfb->cb_db, e, text );
5920         else
5921                 return NOID;
5922 }
5923
5924 static struct {
5925         char *name;
5926         AttributeDescription **desc;
5927 } ads[] = {
5928         { "attribute", &cfAd_attr },
5929         { "backend", &cfAd_backend },
5930         { "database", &cfAd_database },
5931         { "include", &cfAd_include },
5932         { "objectclass", &cfAd_oc },
5933         { "objectidentifier", &cfAd_om },
5934         { "overlay", &cfAd_overlay },
5935         { NULL, NULL }
5936 };
5937
5938 /* Notes:
5939  *   add / delete: all types that may be added or deleted must use an
5940  * X-ORDERED attributeType for their RDN. Adding and deleting entries
5941  * should automatically renumber the index of any siblings as needed,
5942  * so that no gaps in the numbering sequence exist after the add/delete
5943  * is completed.
5944  *   What can be added:
5945  *     schema objects
5946  *     backend objects for backend-specific config directives
5947  *     database objects
5948  *     overlay objects
5949  *
5950  *   delete: probably no support this time around.
5951  *
5952  *   modrdn: generally not done. Will be invoked automatically by add/
5953  * delete to update numbering sequence. Perform as an explicit operation
5954  * so that the renumbering effect may be replicated. Subtree rename must
5955  * be supported, since renumbering a database will affect all its child
5956  * overlays.
5957  *
5958  *  modify: must be fully supported. 
5959  */
5960
5961 int
5962 config_back_initialize( BackendInfo *bi )
5963 {
5964         ConfigTable             *ct = config_back_cf_table;
5965         ConfigArgs ca;
5966         char                    *argv[4];
5967         int                     i;
5968         AttributeDescription    *ad = NULL;
5969         const char              *text;
5970         static char             *controls[] = {
5971                 LDAP_CONTROL_MANAGEDSAIT,
5972                 NULL
5973         };
5974
5975         /* Make sure we don't exceed the bits reserved for userland */
5976         config_check_userland( CFG_LAST );
5977
5978         bi->bi_controls = controls;
5979
5980         bi->bi_open = 0;
5981         bi->bi_close = 0;
5982         bi->bi_config = 0;
5983         bi->bi_destroy = config_back_destroy;
5984
5985         bi->bi_db_init = config_back_db_init;
5986         bi->bi_db_config = 0;
5987         bi->bi_db_open = config_back_db_open;
5988         bi->bi_db_close = config_back_db_close;
5989         bi->bi_db_destroy = config_back_db_destroy;
5990
5991         bi->bi_op_bind = config_back_bind;
5992         bi->bi_op_unbind = 0;
5993         bi->bi_op_search = config_back_search;
5994         bi->bi_op_compare = 0;
5995         bi->bi_op_modify = config_back_modify;
5996         bi->bi_op_modrdn = config_back_modrdn;
5997         bi->bi_op_add = config_back_add;
5998         bi->bi_op_delete = config_back_delete;
5999         bi->bi_op_abandon = 0;
6000
6001         bi->bi_extended = 0;
6002
6003         bi->bi_chk_referrals = 0;
6004
6005         bi->bi_access_allowed = slap_access_allowed;
6006
6007         bi->bi_connection_init = 0;
6008         bi->bi_connection_destroy = 0;
6009
6010         bi->bi_entry_release_rw = config_entry_release;
6011         bi->bi_entry_get_rw = config_back_entry_get;
6012
6013         bi->bi_tool_entry_open = config_tool_entry_open;
6014         bi->bi_tool_entry_close = config_tool_entry_close;
6015         bi->bi_tool_entry_first = config_tool_entry_first;
6016         bi->bi_tool_entry_next = config_tool_entry_next;
6017         bi->bi_tool_entry_get = config_tool_entry_get;
6018         bi->bi_tool_entry_put = config_tool_entry_put;
6019
6020         ca.argv = argv;
6021         argv[ 0 ] = "slapd";
6022         ca.argv = argv;
6023         ca.argc = 3;
6024         ca.fname = argv[0];
6025
6026         argv[3] = NULL;
6027         for (i=0; OidMacros[i].name; i++ ) {
6028                 argv[1] = OidMacros[i].name;
6029                 argv[2] = OidMacros[i].oid;
6030                 parse_oidm( &ca, 0, NULL );
6031         }
6032
6033         bi->bi_cf_ocs = cf_ocs;
6034
6035         i = config_register_schema( ct, cf_ocs );
6036         if ( i ) return i;
6037
6038         /* setup olcRootPW to be base64-encoded when written in LDIF form;
6039          * basically, we don't care if it fails */
6040         i = slap_str2ad( "olcRootPW", &ad, &text );
6041         if ( i ) {
6042                 Debug( LDAP_DEBUG_ANY, "config_back_initialize: "
6043                         "warning, unable to get \"olcRootPW\" "
6044                         "attribute description: %d: %s\n",
6045                         i, text, 0 );
6046         } else {
6047                 (void)ldif_must_b64_encode_register( ad->ad_cname.bv_val,
6048                         ad->ad_type->sat_oid );
6049         }
6050
6051         /* set up the notable AttributeDescriptions */
6052         i = 0;
6053         for (;ct->name;ct++) {
6054                 if (strcmp(ct->name, ads[i].name)) continue;
6055                 *ads[i].desc = ct->ad;
6056                 i++;
6057                 if (!ads[i].name) break;
6058         }
6059
6060         return 0;
6061 }
6062