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