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