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