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