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