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