]> git.sur5r.net Git - openldap/blob - servers/slapd/config.c
7f91d5ec87234ed395037713341323ec7b9518d5
[openldap] / servers / slapd / config.c
1 /* config.c - configuration file handling routines */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2009 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms are permitted
20  * provided that this notice is preserved and that due credit is given
21  * to the University of Michigan at Ann Arbor. The name of the University
22  * may not be used to endorse or promote products derived from this
23  * software without specific prior written permission. This software
24  * is provided ``as is'' without express or implied warranty.
25  */
26
27 #include "portable.h"
28
29 #include <stdio.h>
30
31 #include <ac/string.h>
32 #include <ac/ctype.h>
33 #include <ac/signal.h>
34 #include <ac/socket.h>
35 #include <ac/errno.h>
36 #include <ac/unistd.h>
37
38 #include <sys/types.h>
39 #include <sys/stat.h>
40
41 #ifndef S_ISREG
42 #define S_ISREG(m)      (((m) & _S_IFMT) == _S_IFREG)
43 #endif
44
45 #include "slap.h"
46 #ifdef LDAP_SLAPI
47 #include "slapi/slapi.h"
48 #endif
49 #include "lutil.h"
50 #include "lutil_ldap.h"
51 #include "config.h"
52
53 #define ARGS_STEP       512
54
55 /*
56  * defaults for various global variables
57  */
58 slap_mask_t             global_allows = 0;
59 slap_mask_t             global_disallows = 0;
60 int             global_gentlehup = 0;
61 int             global_idletimeout = 0;
62 int             global_writetimeout = 0;
63 char    *global_host = NULL;
64 struct berval global_host_bv = BER_BVNULL;
65 char    *global_realm = NULL;
66 char    *sasl_host = NULL;
67 char            **default_passwd_hash = NULL;
68 struct berval default_search_base = BER_BVNULL;
69 struct berval default_search_nbase = BER_BVNULL;
70
71 ber_len_t sockbuf_max_incoming = SLAP_SB_MAX_INCOMING_DEFAULT;
72 ber_len_t sockbuf_max_incoming_auth= SLAP_SB_MAX_INCOMING_AUTH;
73
74 int     slap_conn_max_pending = SLAP_CONN_MAX_PENDING_DEFAULT;
75 int     slap_conn_max_pending_auth = SLAP_CONN_MAX_PENDING_AUTH;
76
77 char   *slapd_pid_file  = NULL;
78 char   *slapd_args_file = NULL;
79
80 int use_reverse_lookup = 0;
81
82 #ifdef LDAP_SLAPI
83 int slapi_plugins_used = 0;
84 #endif
85
86 static int fp_getline(FILE *fp, ConfigArgs *c);
87 static void fp_getline_init(ConfigArgs *c);
88
89 static char     *strtok_quote(char *line, char *sep, char **quote_ptr);
90 static char *strtok_quote_ldif(char **line);
91
92 ConfigArgs *
93 new_config_args( BackendDB *be, const char *fname, int lineno, int argc, char **argv )
94 {
95         ConfigArgs *c;
96         c = ch_calloc( 1, sizeof( ConfigArgs ) );
97         if ( c == NULL ) return(NULL);
98         c->be     = be; 
99         c->fname  = fname;
100         c->argc   = argc;
101         c->argv   = argv; 
102         c->lineno = lineno;
103         snprintf( c->log, sizeof( c->log ), "%s: line %d", fname, lineno );
104         return(c);
105 }
106
107 void
108 init_config_argv( ConfigArgs *c )
109 {
110         c->argv = ch_calloc( ARGS_STEP + 1, sizeof( *c->argv ) );
111         c->argv_size = ARGS_STEP + 1;
112 }
113
114 ConfigTable *config_find_keyword(ConfigTable *Conf, ConfigArgs *c) {
115         int i;
116
117         for(i = 0; Conf[i].name; i++)
118                 if( (Conf[i].length && (!strncasecmp(c->argv[0], Conf[i].name, Conf[i].length))) ||
119                         (!strcasecmp(c->argv[0], Conf[i].name)) ) break;
120         if ( !Conf[i].name ) return NULL;
121         return Conf+i;
122 }
123
124 int config_check_vals(ConfigTable *Conf, ConfigArgs *c, int check_only ) {
125         int rc, arg_user, arg_type, arg_syn, iarg;
126         unsigned uiarg;
127         long larg;
128         unsigned long ularg;
129         ber_len_t barg;
130         
131         if(Conf->arg_type == ARG_IGNORED) {
132                 Debug(LDAP_DEBUG_CONFIG, "%s: keyword <%s> ignored\n",
133                         c->log, Conf->name, 0);
134                 return(0);
135         }
136         arg_type = Conf->arg_type & ARGS_TYPES;
137         arg_user = Conf->arg_type & ARGS_USERLAND;
138         arg_syn = Conf->arg_type & ARGS_SYNTAX;
139
140         if((arg_type == ARG_DN) && c->argc == 1) {
141                 c->argc = 2;
142                 c->argv[1] = "";
143         }
144         if(Conf->min_args && (c->argc < Conf->min_args)) {
145                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> missing <%s> argument",
146                         c->argv[0], Conf->what ? Conf->what : "" );
147                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: keyword %s\n", c->log, c->cr_msg, 0 );
148                 return(ARG_BAD_CONF);
149         }
150         if(Conf->max_args && (c->argc > Conf->max_args)) {
151                 char    *ignored = " ignored";
152
153                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> extra cruft after <%s>",
154                         c->argv[0], Conf->what );
155
156                 ignored = "";
157                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s%s.\n",
158                                 c->log, c->cr_msg, ignored );
159                 return(ARG_BAD_CONF);
160         }
161         if((arg_syn & ARG_DB) && !c->be) {
162                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> only allowed within database declaration",
163                         c->argv[0] );
164                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: keyword %s\n",
165                         c->log, c->cr_msg, 0);
166                 return(ARG_BAD_CONF);
167         }
168         if((arg_syn & ARG_PRE_BI) && c->bi) {
169                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> must occur before any backend %sdeclaration",
170                         c->argv[0], (arg_syn & ARG_PRE_DB) ? "or database " : "" );
171                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: keyword %s\n",
172                         c->log, c->cr_msg, 0 );
173                 return(ARG_BAD_CONF);
174         }
175         if((arg_syn & ARG_PRE_DB) && c->be && c->be != frontendDB) {
176                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> must occur before any database declaration",
177                         c->argv[0] );
178                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: keyword %s\n",
179                         c->log, c->cr_msg, 0);
180                 return(ARG_BAD_CONF);
181         }
182         if((arg_syn & ARG_PAREN) && *c->argv[1] != '(' /*')'*/) {
183                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> old format not supported", c->argv[0] );
184                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
185                         c->log, c->cr_msg, 0);
186                 return(ARG_BAD_CONF);
187         }
188         if(arg_type && !Conf->arg_item && !(arg_syn & ARG_OFFSET)) {
189                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid config_table, arg_item is NULL",
190                         c->argv[0] );
191                 Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
192                         c->log, c->cr_msg, 0);
193                 return(ARG_BAD_CONF);
194         }
195         c->type = arg_user;
196         memset(&c->values, 0, sizeof(c->values));
197         if(arg_type == ARG_STRING) {
198                 if ( !check_only )
199                         c->value_string = ch_strdup(c->argv[1]);
200         } else if(arg_type == ARG_BERVAL) {
201                 if ( !check_only )
202                         ber_str2bv( c->argv[1], 0, 1, &c->value_bv );
203         } else if(arg_type == ARG_DN) {
204                 struct berval bv;
205                 ber_str2bv( c->argv[1], 0, 0, &bv );
206                 rc = dnPrettyNormal( NULL, &bv, &c->value_dn, &c->value_ndn, NULL );
207                 if ( rc != LDAP_SUCCESS ) {
208                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid DN %d (%s)",
209                                 c->argv[0], rc, ldap_err2string( rc ));
210                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n" , c->log, c->cr_msg, 0);
211                         return(ARG_BAD_CONF);
212                 }
213                 if ( check_only ) {
214                         ch_free( c->value_ndn.bv_val );
215                         ch_free( c->value_dn.bv_val );
216                 }
217         } else if(arg_type == ARG_ATDESC) {
218                 const char *text = NULL;
219                 c->value_ad = NULL;
220                 rc = slap_str2ad( c->argv[1], &c->value_ad, &text );
221                 if ( rc != LDAP_SUCCESS ) {
222                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid AttributeDescription %d (%s)",
223                                 c->argv[0], rc, text );
224                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n" , c->log, c->cr_msg, 0);
225                         return(ARG_BAD_CONF);
226                 }
227         } else {        /* all numeric */
228                 int j;
229                 iarg = 0; larg = 0; barg = 0;
230                 switch(arg_type) {
231                         case ARG_INT:
232                                 if ( lutil_atoix( &iarg, c->argv[1], 0 ) != 0 ) {
233                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
234                                                 "<%s> unable to parse \"%s\" as int",
235                                                 c->argv[0], c->argv[1] );
236                                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
237                                                 c->log, c->cr_msg, 0);
238                                         return(ARG_BAD_CONF);
239                                 }
240                                 break;
241                         case ARG_UINT:
242                                 if ( lutil_atoux( &uiarg, c->argv[1], 0 ) != 0 ) {
243                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
244                                                 "<%s> unable to parse \"%s\" as unsigned int",
245                                                 c->argv[0], c->argv[1] );
246                                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
247                                                 c->log, c->cr_msg, 0);
248                                         return(ARG_BAD_CONF);
249                                 }
250                                 break;
251                         case ARG_LONG:
252                                 if ( lutil_atolx( &larg, c->argv[1], 0 ) != 0 ) {
253                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
254                                                 "<%s> unable to parse \"%s\" as long",
255                                                 c->argv[0], c->argv[1] );
256                                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
257                                                 c->log, c->cr_msg, 0);
258                                         return(ARG_BAD_CONF);
259                                 }
260                                 break;
261                         case ARG_ULONG:
262                                 if ( lutil_atoulx( &ularg, c->argv[1], 0 ) != 0 ) {
263                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
264                                                 "<%s> unable to parse \"%s\" as unsigned long",
265                                                 c->argv[0], c->argv[1] );
266                                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
267                                                 c->log, c->cr_msg, 0);
268                                         return(ARG_BAD_CONF);
269                                 }
270                                 break;
271                         case ARG_BER_LEN_T: {
272                                 unsigned long   l;
273                                 if ( lutil_atoulx( &l, c->argv[1], 0 ) != 0 ) {
274                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
275                                                 "<%s> unable to parse \"%s\" as ber_len_t",
276                                                 c->argv[0], c->argv[1] );
277                                         Debug(LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE, "%s: %s\n",
278                                                 c->log, c->cr_msg, 0);
279                                         return(ARG_BAD_CONF);
280                                 }
281                                 barg = (ber_len_t)l;
282                                 } break;
283                         case ARG_ON_OFF:
284                                 if (c->argc == 1) {
285                                         iarg = 1;
286                                 } else if ( !strcasecmp(c->argv[1], "on") ||
287                                         !strcasecmp(c->argv[1], "true") ||
288                                         !strcasecmp(c->argv[1], "yes") )
289                                 {
290                                         iarg = 1;
291                                 } else if ( !strcasecmp(c->argv[1], "off") ||
292                                         !strcasecmp(c->argv[1], "false") ||
293                                         !strcasecmp(c->argv[1], "no") )
294                                 {
295                                         iarg = 0;
296                                 } else {
297                                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value",
298                                                 c->argv[0] );
299                                         Debug(LDAP_DEBUG_ANY|LDAP_DEBUG_NONE, "%s: %s\n",
300                                                 c->log, c->cr_msg, 0 );
301                                         return(ARG_BAD_CONF);
302                                 }
303                                 break;
304                 }
305                 j = (arg_type & ARG_NONZERO) ? 1 : 0;
306                 if(iarg < j && larg < j && barg < (unsigned)j ) {
307                         larg = larg ? larg : (barg ? (long)barg : iarg);
308                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> invalid value",
309                                 c->argv[0] );
310                         Debug(LDAP_DEBUG_ANY|LDAP_DEBUG_NONE, "%s: %s\n",
311                                 c->log, c->cr_msg, 0 );
312                         return(ARG_BAD_CONF);
313                 }
314                 switch(arg_type) {
315                         case ARG_ON_OFF:
316                         case ARG_INT:           c->value_int = iarg;            break;
317                         case ARG_UINT:          c->value_uint = uiarg;          break;
318                         case ARG_LONG:          c->value_long = larg;           break;
319                         case ARG_ULONG:         c->value_ulong = ularg;         break;
320                         case ARG_BER_LEN_T:     c->value_ber_t = barg;          break;
321                 }
322         }
323         return 0;
324 }
325
326 int config_set_vals(ConfigTable *Conf, ConfigArgs *c) {
327         int rc, arg_type;
328         void *ptr = NULL;
329
330         arg_type = Conf->arg_type;
331         if(arg_type & ARG_MAGIC) {
332                 if(!c->be) c->be = frontendDB;
333                 c->cr_msg[0] = '\0';
334                 rc = (*((ConfigDriver*)Conf->arg_item))(c);
335 #if 0
336                 if(c->be == frontendDB) c->be = NULL;
337 #endif
338                 if(rc) {
339                         if ( !c->cr_msg[0] ) {
340                                 snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> handler exited with %d",
341                                         c->argv[0], rc );
342                                 Debug(LDAP_DEBUG_CONFIG, "%s: %s!\n",
343                                         c->log, c->cr_msg, 0 );
344                         }
345                         return(ARG_BAD_CONF);
346                 }
347                 return(0);
348         }
349         if(arg_type & ARG_OFFSET) {
350                 if (c->be && c->table == Cft_Database)
351                         ptr = c->be->be_private;
352                 else if (c->bi)
353                         ptr = c->bi->bi_private;
354                 else {
355                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "<%s> offset is missing base pointer",
356                                 c->argv[0] );
357                         Debug(LDAP_DEBUG_CONFIG, "%s: %s!\n",
358                                 c->log, c->cr_msg, 0);
359                         return(ARG_BAD_CONF);
360                 }
361                 ptr = (void *)((char *)ptr + (long)Conf->arg_item);
362         } else if (arg_type & ARGS_TYPES) {
363                 ptr = Conf->arg_item;
364         }
365         if(arg_type & ARGS_TYPES)
366                 switch(arg_type & ARGS_TYPES) {
367                         case ARG_ON_OFF:
368                         case ARG_INT:           *(int*)ptr = c->value_int;                      break;
369                         case ARG_UINT:          *(unsigned*)ptr = c->value_uint;                        break;
370                         case ARG_LONG:          *(long*)ptr = c->value_long;                    break;
371                         case ARG_ULONG:         *(unsigned long*)ptr = c->value_ulong;                  break;
372                         case ARG_BER_LEN_T:     *(ber_len_t*)ptr = c->value_ber_t;                      break;
373                         case ARG_STRING: {
374                                 char *cc = *(char**)ptr;
375                                 if(cc) {
376                                         if ((arg_type & ARG_UNIQUE) && c->op == SLAP_CONFIG_ADD ) {
377                                                 Debug(LDAP_DEBUG_CONFIG, "%s: already set %s!\n",
378                                                         c->log, Conf->name, 0 );
379                                                 return(ARG_BAD_CONF);
380                                         }
381                                         ch_free(cc);
382                                 }
383                                 *(char **)ptr = c->value_string;
384                                 break;
385                                 }
386                         case ARG_BERVAL:
387                                 *(struct berval *)ptr = c->value_bv;
388                                 break;
389                         case ARG_ATDESC:
390                                 *(AttributeDescription **)ptr = c->value_ad;
391                                 break;
392                 }
393         return(0);
394 }
395
396 int config_add_vals(ConfigTable *Conf, ConfigArgs *c) {
397         int rc, arg_type;
398
399         arg_type = Conf->arg_type;
400         if(arg_type == ARG_IGNORED) {
401                 Debug(LDAP_DEBUG_CONFIG, "%s: keyword <%s> ignored\n",
402                         c->log, Conf->name, 0);
403                 return(0);
404         }
405         rc = config_check_vals( Conf, c, 0 );
406         if ( rc ) return rc;
407         return config_set_vals( Conf, c );
408 }
409
410 int
411 config_del_vals(ConfigTable *cf, ConfigArgs *c)
412 {
413         int rc = 0;
414
415         /* If there is no handler, just ignore it */
416         if ( cf->arg_type & ARG_MAGIC ) {
417                 c->argv[0] = cf->ad->ad_cname.bv_val;
418                 c->op = LDAP_MOD_DELETE;
419                 c->type = cf->arg_type & ARGS_USERLAND;
420                 rc = (*((ConfigDriver*)cf->arg_item))(c);
421         }
422         return rc;
423 }
424
425 int
426 config_get_vals(ConfigTable *cf, ConfigArgs *c)
427 {
428         int rc = 0;
429         struct berval bv;
430         void *ptr;
431
432         if ( cf->arg_type & ARG_IGNORED ) {
433                 return 1;
434         }
435
436         memset(&c->values, 0, sizeof(c->values));
437         c->rvalue_vals = NULL;
438         c->rvalue_nvals = NULL;
439         c->op = SLAP_CONFIG_EMIT;
440         c->type = cf->arg_type & ARGS_USERLAND;
441
442         if ( cf->arg_type & ARG_MAGIC ) {
443                 rc = (*((ConfigDriver*)cf->arg_item))(c);
444                 if ( rc ) return rc;
445         } else {
446                 if ( cf->arg_type & ARG_OFFSET ) {
447                         if (c->be && c->table == Cft_Database)
448                                 ptr = c->be->be_private;
449                         else if ( c->bi )
450                                 ptr = c->bi->bi_private;
451                         else
452                                 return 1;
453                         ptr = (void *)((char *)ptr + (long)cf->arg_item);
454                 } else {
455                         ptr = cf->arg_item;
456                 }
457                 
458                 switch(cf->arg_type & ARGS_TYPES) {
459                 case ARG_ON_OFF:
460                 case ARG_INT:   c->value_int = *(int *)ptr; break;
461                 case ARG_UINT:  c->value_uint = *(unsigned *)ptr; break;
462                 case ARG_LONG:  c->value_long = *(long *)ptr; break;
463                 case ARG_ULONG: c->value_ulong = *(unsigned long *)ptr; break;
464                 case ARG_BER_LEN_T:     c->value_ber_t = *(ber_len_t *)ptr; break;
465                 case ARG_STRING:
466                         if ( *(char **)ptr )
467                                 c->value_string = ch_strdup(*(char **)ptr);
468                         break;
469                 case ARG_BERVAL:
470                         ber_dupbv( &c->value_bv, (struct berval *)ptr ); break;
471                 case ARG_ATDESC:
472                         c->value_ad = *(AttributeDescription **)ptr; break;
473                 }
474         }
475         if ( cf->arg_type & ARGS_TYPES) {
476                 bv.bv_len = 0;
477                 bv.bv_val = c->log;
478                 switch(cf->arg_type & ARGS_TYPES) {
479                 case ARG_INT: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%d", c->value_int); break;
480                 case ARG_UINT: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%u", c->value_uint); break;
481                 case ARG_LONG: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%ld", c->value_long); break;
482                 case ARG_ULONG: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%lu", c->value_ulong); break;
483                 case ARG_BER_LEN_T: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%ld", c->value_ber_t); break;
484                 case ARG_ON_OFF: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%s",
485                         c->value_int ? "TRUE" : "FALSE"); break;
486                 case ARG_STRING:
487                         if ( c->value_string && c->value_string[0]) {
488                                 ber_str2bv( c->value_string, 0, 0, &bv);
489                         } else {
490                                 return 1;
491                         }
492                         break;
493                 case ARG_BERVAL:
494                         if ( !BER_BVISEMPTY( &c->value_bv )) {
495                                 bv = c->value_bv;
496                         } else {
497                                 return 1;
498                         }
499                         break;
500                 case ARG_ATDESC:
501                         if ( c->value_ad ) {
502                                 bv = c->value_ad->ad_cname;
503                         } else {
504                                 return 1;
505                         }
506                         break;
507                 default:
508                         bv.bv_val = NULL;
509                         break;
510                 }
511                 if (bv.bv_val == c->log && bv.bv_len >= sizeof( c->log ) ) {
512                         return 1;
513                 }
514                 if (( cf->arg_type & ARGS_TYPES ) == ARG_STRING ) {
515                         ber_bvarray_add(&c->rvalue_vals, &bv);
516                 } else if ( !BER_BVISNULL( &bv ) ) {
517                         value_add_one(&c->rvalue_vals, &bv);
518                 }
519                 /* else: maybe c->rvalue_vals already set? */
520         }
521         return rc;
522 }
523
524 int
525 init_config_attrs(ConfigTable *ct) {
526         int i, code;
527
528         for (i=0; ct[i].name; i++ ) {
529                 if ( !ct[i].attribute ) continue;
530                 code = register_at( ct[i].attribute, &ct[i].ad, 1 );
531                 if ( code ) {
532                         fprintf( stderr, "init_config_attrs: register_at failed\n" );
533                         return code;
534                 }
535         }
536
537         return 0;
538 }
539
540 int
541 init_config_ocs( ConfigOCs *ocs ) {
542         int i, code;
543
544         for (i=0;ocs[i].co_def;i++) {
545                 code = register_oc( ocs[i].co_def, &ocs[i].co_oc, 1 );
546                 if ( code ) {
547                         fprintf( stderr, "init_config_ocs: register_oc failed\n" );
548                         return code;
549                 }
550         }
551         return 0;
552 }
553
554 /* Split an LDIF line into space-separated tokens. Words may be grouped
555  * by quotes. A quoted string may begin in the middle of a word, but must
556  * end at the end of the word (be followed by whitespace or EOS). Any other
557  * quotes are passed through unchanged. All other characters are passed
558  * through unchanged.
559  */
560 static char *
561 strtok_quote_ldif( char **line )
562 {
563         char *beg, *ptr, *quote=NULL;
564         int inquote=0;
565
566         ptr = *line;
567
568         if ( !ptr || !*ptr )
569                 return NULL;
570
571         while( isspace( (unsigned char) *ptr )) ptr++;
572
573         if ( *ptr == '"' ) {
574                 inquote = 1;
575                 ptr++;
576         }
577
578         beg = ptr;
579
580         for (;*ptr;ptr++) {
581                 if ( *ptr == '"' ) {
582                         if ( inquote && ( !ptr[1] || isspace((unsigned char) ptr[1]))) {
583                                 *ptr++ = '\0';
584                                 break;
585                         }
586                         inquote = 1;
587                         quote = ptr;
588                         continue;
589                 }
590                 if ( inquote )
591                         continue;
592                 if ( isspace( (unsigned char) *ptr )) {
593                         *ptr++ = '\0';
594                         break;
595                 }
596         }
597         if ( quote ) {
598                 while ( quote < ptr ) {
599                         *quote = quote[1];
600                         quote++;
601                 }
602         }
603         if ( !*ptr ) {
604                 *line = NULL;
605         } else {
606                 while ( isspace( (unsigned char) *ptr )) ptr++;
607                 *line = ptr;
608         }
609         return beg;
610 }
611
612 static void
613 config_parse_ldif( ConfigArgs *c )
614 {
615         char *next;
616         c->tline = ch_strdup(c->line);
617         next = c->tline;
618
619         while ((c->argv[c->argc] = strtok_quote_ldif( &next )) != NULL) {
620                 c->argc++;
621                 if ( c->argc >= c->argv_size ) {
622                         char **tmp = ch_realloc( c->argv, (c->argv_size + ARGS_STEP) *
623                                 sizeof( *c->argv ));
624                         c->argv = tmp;
625                         c->argv_size += ARGS_STEP;
626                 }
627         }
628         c->argv[c->argc] = NULL;
629 }
630
631 int
632 config_parse_vals(ConfigTable *ct, ConfigArgs *c, int valx)
633 {
634         int     rc = 0;
635
636         snprintf( c->log, sizeof( c->log ), "%s: value #%d",
637                 ct->ad->ad_cname.bv_val, valx );
638         c->argc = 1;
639         c->argv[0] = ct->ad->ad_cname.bv_val;
640
641         if ( ( ct->arg_type & ARG_QUOTE ) && c->line[ 0 ] != '"' ) {
642                 c->argv[c->argc] = c->line;
643                 c->argc++;
644                 c->argv[c->argc] = NULL;
645                 c->tline = NULL;
646         } else {
647                 config_parse_ldif( c );
648         }
649         rc = config_check_vals( ct, c, 1 );
650         ch_free( c->tline );
651         c->tline = NULL;
652
653         if ( rc )
654                 rc = LDAP_CONSTRAINT_VIOLATION;
655
656         return rc;
657 }
658
659 int
660 config_parse_add(ConfigTable *ct, ConfigArgs *c, int valx)
661 {
662         int     rc = 0;
663
664         snprintf( c->log, sizeof( c->log ), "%s: value #%d",
665                 ct->ad->ad_cname.bv_val, valx );
666         c->argc = 1;
667         c->argv[0] = ct->ad->ad_cname.bv_val;
668
669         if ( ( ct->arg_type & ARG_QUOTE ) && c->line[ 0 ] != '"' ) {
670                 c->argv[c->argc] = c->line;
671                 c->argc++;
672                 c->argv[c->argc] = NULL;
673                 c->tline = NULL;
674         } else {
675                 config_parse_ldif( c );
676         }
677         c->op = LDAP_MOD_ADD;
678         rc = config_add_vals( ct, c );
679         ch_free( c->tline );
680
681         return rc;
682 }
683
684 int
685 read_config_file(const char *fname, int depth, ConfigArgs *cf, ConfigTable *cft)
686 {
687         FILE *fp;
688         ConfigTable *ct;
689         ConfigArgs *c;
690         int rc;
691         struct stat s;
692
693         c = ch_calloc( 1, sizeof( ConfigArgs ) );
694         if ( c == NULL ) {
695                 return 1;
696         }
697
698         if ( depth ) {
699                 memcpy( c, cf, sizeof( ConfigArgs ) );
700         } else {
701                 c->depth = depth; /* XXX */
702                 c->bi = NULL;
703                 c->be = NULL;
704         }
705
706         c->valx = -1;
707         c->fname = fname;
708         init_config_argv( c );
709
710         if ( stat( fname, &s ) != 0 ) {
711                 ldap_syslog = 1;
712                 Debug(LDAP_DEBUG_ANY,
713                     "could not stat config file \"%s\": %s (%d)\n",
714                     fname, strerror(errno), errno);
715                 ch_free( c );
716                 return(1);
717         }
718
719         if ( !S_ISREG( s.st_mode ) ) {
720                 ldap_syslog = 1;
721                 Debug(LDAP_DEBUG_ANY,
722                     "regular file expected, got \"%s\"\n",
723                     fname, 0, 0 );
724                 ch_free( c );
725                 return(1);
726         }
727
728         fp = fopen( fname, "r" );
729         if ( fp == NULL ) {
730                 ldap_syslog = 1;
731                 Debug(LDAP_DEBUG_ANY,
732                     "could not open config file \"%s\": %s (%d)\n",
733                     fname, strerror(errno), errno);
734                 ch_free( c );
735                 return(1);
736         }
737
738         Debug(LDAP_DEBUG_CONFIG, "reading config file %s\n", fname, 0, 0);
739
740         fp_getline_init(c);
741
742         c->tline = NULL;
743
744         while ( fp_getline( fp, c ) ) {
745                 /* skip comments and blank lines */
746                 if ( c->line[0] == '#' || c->line[0] == '\0' ) {
747                         continue;
748                 }
749
750                 snprintf( c->log, sizeof( c->log ), "%s: line %d",
751                                 c->fname, c->lineno );
752
753                 c->argc = 0;
754                 ch_free( c->tline );
755                 if ( config_fp_parse_line( c ) ) {
756                         rc = 1;
757                         goto done;
758                 }
759
760                 if ( c->argc < 1 ) {
761                         Debug( LDAP_DEBUG_ANY, "%s: bad config line.\n",
762                                 c->log, 0, 0);
763                         rc = 1;
764                         goto done;
765                 }
766
767                 c->op = SLAP_CONFIG_ADD;
768
769                 ct = config_find_keyword( cft, c );
770                 if ( ct ) {
771                         c->table = Cft_Global;
772                         rc = config_add_vals( ct, c );
773                         if ( !rc ) continue;
774
775                         if ( rc & ARGS_USERLAND ) {
776                                 /* XXX a usertype would be opaque here */
777                                 Debug(LDAP_DEBUG_CONFIG, "%s: unknown user type <%s>\n",
778                                         c->log, c->argv[0], 0);
779                                 rc = 1;
780                                 goto done;
781
782                         } else if ( rc == ARG_BAD_CONF ) {
783                                 rc = 1;
784                                 goto done;
785                         }
786                         
787                 } else if ( c->bi && !c->be ) {
788                         rc = SLAP_CONF_UNKNOWN;
789                         if ( c->bi->bi_cf_ocs ) {
790                                 ct = config_find_keyword( c->bi->bi_cf_ocs->co_table, c );
791                                 if ( ct ) {
792                                         c->table = c->bi->bi_cf_ocs->co_type;
793                                         rc = config_add_vals( ct, c );
794                                 }
795                         }
796                         if ( c->bi->bi_config && rc == SLAP_CONF_UNKNOWN ) {
797                                 rc = (*c->bi->bi_config)(c->bi, c->fname, c->lineno,
798                                         c->argc, c->argv);
799                         }
800                         if ( rc ) {
801                                 switch(rc) {
802                                 case SLAP_CONF_UNKNOWN:
803                                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
804                                                 "<%s> inside backend info definition.\n",
805                                                 c->log, *c->argv, 0);
806                                 default:
807                                         rc = 1;
808                                         goto done;
809                                 }
810                         }
811
812                 } else if ( c->be && c->be != frontendDB ) {
813                         rc = SLAP_CONF_UNKNOWN;
814                         if ( c->be->be_cf_ocs ) {
815                                 ct = config_find_keyword( c->be->be_cf_ocs->co_table, c );
816                                 if ( ct ) {
817                                         c->table = c->be->be_cf_ocs->co_type;
818                                         rc = config_add_vals( ct, c );
819                                 }
820                         }
821                         if ( c->be->be_config && rc == SLAP_CONF_UNKNOWN ) {
822                                 rc = (*c->be->be_config)(c->be, c->fname, c->lineno,
823                                         c->argc, c->argv);
824                         }
825                         if ( rc == SLAP_CONF_UNKNOWN && SLAP_ISGLOBALOVERLAY( frontendDB ) )
826                         {
827                                 /* global overlays may need 
828                                  * definitions inside other databases...
829                                  */
830                                 rc = (*frontendDB->be_config)( frontendDB,
831                                         c->fname, (int)c->lineno, c->argc, c->argv );
832                         }
833
834                         switch ( rc ) {
835                         case 0:
836                                 break;
837
838                         case SLAP_CONF_UNKNOWN:
839                                 Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
840                                         "<%s> inside backend database definition.\n",
841                                         c->log, *c->argv, 0);
842                                 
843                         default:
844                                 rc = 1;
845                                 goto done;
846                         }
847
848                 } else if ( frontendDB->be_config ) {
849                         rc = (*frontendDB->be_config)( frontendDB,
850                                 c->fname, (int)c->lineno, c->argc, c->argv);
851                         if ( rc ) {
852                                 switch(rc) {
853                                 case SLAP_CONF_UNKNOWN:
854                                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
855                                                 "<%s> inside global database definition.\n",
856                                                 c->log, *c->argv, 0);
857
858                                 default:
859                                         rc = 1;
860                                         goto done;
861                                 }
862                         }
863                         
864                 } else {
865                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
866                                 "<%s> outside backend info and database definitions.\n",
867                                 c->log, *c->argv, 0);
868                         rc = 1;
869                         goto done;
870                 }
871         }
872
873         rc = 0;
874
875 done:
876         if ( cf ) {
877                 cf->be = c->be;
878                 cf->bi = c->bi;
879         }
880         ch_free(c->tline);
881         fclose(fp);
882         ch_free(c->argv);
883         ch_free(c);
884         return(rc);
885 }
886
887 /* restrictops, allows, disallows, requires, loglevel */
888
889 int
890 bverb_to_mask(struct berval *bword, slap_verbmasks *v) {
891         int i;
892         for(i = 0; !BER_BVISNULL(&v[i].word); i++) {
893                 if(!ber_bvstrcasecmp(bword, &v[i].word)) break;
894         }
895         return(i);
896 }
897
898 int
899 verb_to_mask(const char *word, slap_verbmasks *v) {
900         struct berval   bword;
901         ber_str2bv( word, 0, 0, &bword );
902         return bverb_to_mask( &bword, v );
903 }
904
905 int
906 verbs_to_mask(int argc, char *argv[], slap_verbmasks *v, slap_mask_t *m) {
907         int i, j;
908         for(i = 1; i < argc; i++) {
909                 j = verb_to_mask(argv[i], v);
910                 if(BER_BVISNULL(&v[j].word)) return i;
911                 while (!v[j].mask) j--;
912                 *m |= v[j].mask;
913         }
914         return(0);
915 }
916
917 /* Mask keywords that represent multiple bits should occur before single
918  * bit keywords in the verbmasks array.
919  */
920 int
921 mask_to_verbs(slap_verbmasks *v, slap_mask_t m, BerVarray *bva) {
922         int i, rc = 1;
923
924         if (m) {
925                 for (i=0; !BER_BVISNULL(&v[i].word); i++) {
926                         if (!v[i].mask) continue;
927                         if (( m & v[i].mask ) == v[i].mask ) {
928                                 value_add_one( bva, &v[i].word );
929                                 rc = 0;
930                                 m ^= v[i].mask;
931                                 if ( !m ) break;
932                         }
933                 }
934         }
935         return rc;
936 }
937
938 int
939 slap_verbmasks_init( slap_verbmasks **vp, slap_verbmasks *v )
940 {
941         int             i;
942
943         assert( *vp == NULL );
944
945         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) /* EMPTY */;
946
947         *vp = ch_calloc( i + 1, sizeof( slap_verbmasks ) );
948
949         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) {
950                 ber_dupbv( &(*vp)[ i ].word, &v[ i ].word );
951                 *((slap_mask_t *)&(*vp)[ i ].mask) = v[ i ].mask;
952         }
953
954         BER_BVZERO( &(*vp)[ i ].word );
955
956         return 0;               
957 }
958
959 int
960 slap_verbmasks_destroy( slap_verbmasks *v )
961 {
962         int             i;
963
964         assert( v != NULL );
965
966         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) {
967                 ch_free( v[ i ].word.bv_val );
968         }
969
970         ch_free( v );
971
972         return 0;
973 }
974
975 int
976 slap_verbmasks_append(
977         slap_verbmasks  **vp,
978         slap_mask_t     m,
979         struct berval   *v,
980         slap_mask_t     *ignore )
981 {
982         int     i;
983
984         if ( !m ) {
985                 return LDAP_OPERATIONS_ERROR;
986         }
987
988         for ( i = 0; !BER_BVISNULL( &(*vp)[ i ].word ); i++ ) {
989                 if ( !(*vp)[ i ].mask ) continue;
990
991                 if ( ignore != NULL ) {
992                         int     j;
993
994                         for ( j = 0; ignore[ j ] != 0; j++ ) {
995                                 if ( (*vp)[ i ].mask == ignore[ j ] ) {
996                                         goto check_next;
997                                 }
998                         }
999                 }
1000
1001                 if ( ( m & (*vp)[ i ].mask ) == (*vp)[ i ].mask ) {
1002                         if ( ber_bvstrcasecmp( v, &(*vp)[ i ].word ) == 0 ) {
1003                                 /* already set; ignore */
1004                                 return LDAP_SUCCESS;
1005                         }
1006                         /* conflicts */
1007                         return LDAP_TYPE_OR_VALUE_EXISTS;
1008                 }
1009
1010                 if ( m & (*vp)[ i ].mask ) {
1011                         /* conflicts */
1012                         return LDAP_CONSTRAINT_VIOLATION;
1013                 }
1014 check_next:;
1015         }
1016
1017         *vp = ch_realloc( *vp, sizeof( slap_verbmasks ) * ( i + 2 ) );
1018         ber_dupbv( &(*vp)[ i ].word, v );
1019         *((slap_mask_t *)&(*vp)[ i ].mask) = m;
1020         BER_BVZERO( &(*vp)[ i + 1 ].word );
1021
1022         return LDAP_SUCCESS;
1023 }
1024
1025 int
1026 enum_to_verb(slap_verbmasks *v, slap_mask_t m, struct berval *bv) {
1027         int i;
1028
1029         for (i=0; !BER_BVISNULL(&v[i].word); i++) {
1030                 if ( m == v[i].mask ) {
1031                         if ( bv != NULL ) {
1032                                 *bv = v[i].word;
1033                         }
1034                         return i;
1035                 }
1036         }
1037         return -1;
1038 }
1039
1040 /* register a new verbmask */
1041 static int
1042 slap_verbmask_register( slap_verbmasks *vm_, slap_verbmasks **vmp, struct berval *bv, int mask )
1043 {
1044         slap_verbmasks  *vm = *vmp;
1045         int             i;
1046
1047         /* check for duplicate word */
1048         /* NOTE: we accept duplicate codes; the first occurrence will be used
1049          * when mapping from mask to verb */
1050         i = verb_to_mask( bv->bv_val, vm );
1051         if ( !BER_BVISNULL( &vm[ i ].word ) ) {
1052                 return -1;
1053         }
1054
1055         for ( i = 0; !BER_BVISNULL( &vm[ i ].word ); i++ )
1056                 ;
1057
1058         if ( vm == vm_ ) {
1059                 /* first time: duplicate array */
1060                 vm = ch_calloc( i + 2, sizeof( slap_verbmasks ) );
1061                 for ( i = 0; !BER_BVISNULL( &vm_[ i ].word ); i++ )
1062                 {
1063                         ber_dupbv( &vm[ i ].word, &vm_[ i ].word );
1064                         *((slap_mask_t*)&vm[ i ].mask) = vm_[ i ].mask;
1065                 }
1066
1067         } else {
1068                 vm = ch_realloc( vm, (i + 2) * sizeof( slap_verbmasks ) );
1069         }
1070
1071         ber_dupbv( &vm[ i ].word, bv );
1072         *((slap_mask_t*)&vm[ i ].mask) = mask;
1073
1074         BER_BVZERO( &vm[ i+1 ].word );
1075
1076         *vmp = vm;
1077
1078         return i;
1079 }
1080
1081 static slap_verbmasks slap_ldap_response_code_[] = {
1082         { BER_BVC("success"),                           LDAP_SUCCESS },
1083
1084         { BER_BVC("operationsError"),                   LDAP_OPERATIONS_ERROR },
1085         { BER_BVC("protocolError"),                     LDAP_PROTOCOL_ERROR },
1086         { BER_BVC("timelimitExceeded"),                 LDAP_TIMELIMIT_EXCEEDED },
1087         { BER_BVC("sizelimitExceeded"),                 LDAP_SIZELIMIT_EXCEEDED },
1088         { BER_BVC("compareFalse"),                      LDAP_COMPARE_FALSE },
1089         { BER_BVC("compareTrue"),                       LDAP_COMPARE_TRUE },
1090
1091         { BER_BVC("authMethodNotSupported"),            LDAP_AUTH_METHOD_NOT_SUPPORTED },
1092         { BER_BVC("strongAuthNotSupported"),            LDAP_STRONG_AUTH_NOT_SUPPORTED },
1093         { BER_BVC("strongAuthRequired"),                LDAP_STRONG_AUTH_REQUIRED },
1094         { BER_BVC("strongerAuthRequired"),              LDAP_STRONGER_AUTH_REQUIRED },
1095 #if 0 /* not LDAPv3 */
1096         { BER_BVC("partialResults"),                    LDAP_PARTIAL_RESULTS },
1097 #endif
1098
1099         { BER_BVC("referral"),                          LDAP_REFERRAL },
1100         { BER_BVC("adminlimitExceeded"),                LDAP_ADMINLIMIT_EXCEEDED },
1101         { BER_BVC("unavailableCriticalExtension"),      LDAP_UNAVAILABLE_CRITICAL_EXTENSION },
1102         { BER_BVC("confidentialityRequired"),           LDAP_CONFIDENTIALITY_REQUIRED },
1103         { BER_BVC("saslBindInProgress"),                LDAP_SASL_BIND_IN_PROGRESS },
1104
1105         { BER_BVC("noSuchAttribute"),                   LDAP_NO_SUCH_ATTRIBUTE },
1106         { BER_BVC("undefinedType"),                     LDAP_UNDEFINED_TYPE },
1107         { BER_BVC("inappropriateMatching"),             LDAP_INAPPROPRIATE_MATCHING },
1108         { BER_BVC("constraintViolation"),               LDAP_CONSTRAINT_VIOLATION },
1109         { BER_BVC("typeOrValueExists"),                 LDAP_TYPE_OR_VALUE_EXISTS },
1110         { BER_BVC("invalidSyntax"),                     LDAP_INVALID_SYNTAX },
1111
1112         { BER_BVC("noSuchObject"),                      LDAP_NO_SUCH_OBJECT },
1113         { BER_BVC("aliasProblem"),                      LDAP_ALIAS_PROBLEM },
1114         { BER_BVC("invalidDnSyntax"),                   LDAP_INVALID_DN_SYNTAX },
1115 #if 0 /* not LDAPv3 */
1116         { BER_BVC("isLeaf"),                            LDAP_IS_LEAF },
1117 #endif
1118         { BER_BVC("aliasDerefProblem"),                 LDAP_ALIAS_DEREF_PROBLEM },
1119
1120         { BER_BVC("proxyAuthzFailure"),                 LDAP_X_PROXY_AUTHZ_FAILURE },
1121         { BER_BVC("inappropriateAuth"),                 LDAP_INAPPROPRIATE_AUTH },
1122         { BER_BVC("invalidCredentials"),                LDAP_INVALID_CREDENTIALS },
1123         { BER_BVC("insufficientAccess"),                LDAP_INSUFFICIENT_ACCESS },
1124
1125         { BER_BVC("busy"),                              LDAP_BUSY },
1126         { BER_BVC("unavailable"),                       LDAP_UNAVAILABLE },
1127         { BER_BVC("unwillingToPerform"),                LDAP_UNWILLING_TO_PERFORM },
1128         { BER_BVC("loopDetect"),                        LDAP_LOOP_DETECT },
1129
1130         { BER_BVC("namingViolation"),                   LDAP_NAMING_VIOLATION },
1131         { BER_BVC("objectClassViolation"),              LDAP_OBJECT_CLASS_VIOLATION },
1132         { BER_BVC("notAllowedOnNonleaf"),               LDAP_NOT_ALLOWED_ON_NONLEAF },
1133         { BER_BVC("notAllowedOnRdn"),                   LDAP_NOT_ALLOWED_ON_RDN },
1134         { BER_BVC("alreadyExists"),                     LDAP_ALREADY_EXISTS },
1135         { BER_BVC("noObjectClassMods"),                 LDAP_NO_OBJECT_CLASS_MODS },
1136         { BER_BVC("resultsTooLarge"),                   LDAP_RESULTS_TOO_LARGE },
1137         { BER_BVC("affectsMultipleDsas"),               LDAP_AFFECTS_MULTIPLE_DSAS },
1138
1139         { BER_BVC("other"),                             LDAP_OTHER },
1140
1141         /* extension-specific */
1142
1143         { BER_BVC("cupResourcesExhausted"),             LDAP_CUP_RESOURCES_EXHAUSTED },
1144         { BER_BVC("cupSecurityViolation"),              LDAP_CUP_SECURITY_VIOLATION },
1145         { BER_BVC("cupInvalidData"),                    LDAP_CUP_INVALID_DATA },
1146         { BER_BVC("cupUnsupportedScheme"),              LDAP_CUP_UNSUPPORTED_SCHEME },
1147         { BER_BVC("cupReloadRequired"),                 LDAP_CUP_RELOAD_REQUIRED },
1148
1149         { BER_BVC("cancelled"),                         LDAP_CANCELLED },
1150         { BER_BVC("noSuchOperation"),                   LDAP_NO_SUCH_OPERATION },
1151         { BER_BVC("tooLate"),                           LDAP_TOO_LATE },
1152         { BER_BVC("cannotCancel"),                      LDAP_CANNOT_CANCEL },
1153
1154         { BER_BVC("assertionFailed"),                   LDAP_ASSERTION_FAILED },
1155
1156         { BER_BVC("proxiedAuthorizationDenied"),        LDAP_PROXIED_AUTHORIZATION_DENIED },
1157
1158         { BER_BVC("syncRefreshRequired"),               LDAP_SYNC_REFRESH_REQUIRED },
1159
1160         { BER_BVC("noOperation"),                       LDAP_X_NO_OPERATION },
1161
1162         { BER_BVNULL,                           0 }
1163 };
1164
1165 slap_verbmasks *slap_ldap_response_code = slap_ldap_response_code_;
1166
1167 int
1168 slap_ldap_response_code_register( struct berval *bv, int err )
1169 {
1170         return slap_verbmask_register( slap_ldap_response_code_,
1171                 &slap_ldap_response_code, bv, err );
1172 }
1173
1174 #ifdef HAVE_TLS
1175 static slap_verbmasks tlskey[] = {
1176         { BER_BVC("no"),        SB_TLS_OFF },
1177         { BER_BVC("yes"),       SB_TLS_ON },
1178         { BER_BVC("critical"),  SB_TLS_CRITICAL },
1179         { BER_BVNULL, 0 }
1180 };
1181
1182 static slap_verbmasks crlkeys[] = {
1183                 { BER_BVC("none"),      LDAP_OPT_X_TLS_CRL_NONE },
1184                 { BER_BVC("peer"),      LDAP_OPT_X_TLS_CRL_PEER },
1185                 { BER_BVC("all"),       LDAP_OPT_X_TLS_CRL_ALL },
1186                 { BER_BVNULL, 0 }
1187         };
1188
1189 static slap_verbmasks vfykeys[] = {
1190                 { BER_BVC("never"),     LDAP_OPT_X_TLS_NEVER },
1191                 { BER_BVC("demand"),    LDAP_OPT_X_TLS_DEMAND },
1192                 { BER_BVC("try"),       LDAP_OPT_X_TLS_TRY },
1193                 { BER_BVC("hard"),      LDAP_OPT_X_TLS_HARD },
1194                 { BER_BVNULL, 0 }
1195         };
1196 #endif
1197
1198 static slap_verbmasks methkey[] = {
1199         { BER_BVC("none"),      LDAP_AUTH_NONE },
1200         { BER_BVC("simple"),    LDAP_AUTH_SIMPLE },
1201 #ifdef HAVE_CYRUS_SASL
1202         { BER_BVC("sasl"),      LDAP_AUTH_SASL },
1203 #endif
1204         { BER_BVNULL, 0 }
1205 };
1206
1207 static slap_verbmasks versionkey[] = {
1208         { BER_BVC("2"),         LDAP_VERSION2 },
1209         { BER_BVC("3"),         LDAP_VERSION3 },
1210         { BER_BVNULL, 0 }
1211 };
1212
1213 static int 
1214 slap_keepalive_parse(
1215         struct berval *val,
1216         void *bc,
1217         slap_cf_aux_table *tab0,
1218         const char *tabmsg,
1219         int unparse )
1220 {
1221         if ( unparse ) {
1222                 slap_keepalive *sk = (slap_keepalive *)bc;
1223                 int rc = snprintf( val->bv_val, val->bv_len, "%d:%d:%d",
1224                         sk->sk_idle, sk->sk_probes, sk->sk_interval );
1225                 if ( rc < 0 ) {
1226                         return -1;
1227                 }
1228
1229                 if ( (unsigned)rc >= val->bv_len ) {
1230                         return -1;
1231                 }
1232
1233                 val->bv_len = rc;
1234
1235         } else {
1236                 char *s = val->bv_val;
1237                 char *next;
1238                 slap_keepalive *sk = (slap_keepalive *)bc;
1239                 slap_keepalive sk2;
1240
1241                 if ( s[0] == ':' ) {
1242                         sk2.sk_idle = 0;
1243                         s++;
1244                         
1245                 } else {
1246                         sk2.sk_idle = strtol( s, &next, 10 );
1247                         if ( next == s || next[0] != ':' ) {
1248                                 return -1;
1249                         }
1250
1251                         if ( sk2.sk_idle < 0 ) {
1252                                 return -1;
1253                         }
1254
1255                         s = ++next;
1256                 }
1257
1258                 if ( s[0] == ':' ) {
1259                         sk2.sk_probes = 0;
1260                         s++;
1261
1262                 } else {
1263                         sk2.sk_probes = strtol( s, &next, 10 );
1264                         if ( next == s || next[0] != ':' ) {
1265                                 return -1;
1266                         }
1267
1268                         if ( sk2.sk_probes < 0 ) {
1269                                 return -1;
1270                         }
1271
1272                         s = ++next;
1273                 }
1274
1275                 if ( s == '\0' ) {
1276                         sk2.sk_interval = 0;
1277                         s++;
1278
1279                 } else {
1280                         sk2.sk_interval = strtol( s, &next, 10 );
1281                         if ( next == s || next[0] != '\0' ) {
1282                                 return -1;
1283                         }
1284
1285                         if ( sk2.sk_interval < 0 ) {
1286                                 return -1;
1287                         }
1288                 }
1289
1290                 *sk = sk2;
1291         }
1292
1293         return 0;
1294 }
1295
1296 static slap_cf_aux_table bindkey[] = {
1297         { BER_BVC("uri="), offsetof(slap_bindconf, sb_uri), 'b', 1, NULL },
1298         { BER_BVC("version="), offsetof(slap_bindconf, sb_version), 'i', 0, versionkey },
1299         { BER_BVC("bindmethod="), offsetof(slap_bindconf, sb_method), 'i', 0, methkey },
1300         { BER_BVC("timeout="), offsetof(slap_bindconf, sb_timeout_api), 'i', 0, NULL },
1301         { BER_BVC("network-timeout="), offsetof(slap_bindconf, sb_timeout_net), 'i', 0, NULL },
1302         { BER_BVC("binddn="), offsetof(slap_bindconf, sb_binddn), 'b', 1, (slap_verbmasks *)dnNormalize },
1303         { BER_BVC("credentials="), offsetof(slap_bindconf, sb_cred), 'b', 1, NULL },
1304         { BER_BVC("saslmech="), offsetof(slap_bindconf, sb_saslmech), 'b', 0, NULL },
1305         { BER_BVC("secprops="), offsetof(slap_bindconf, sb_secprops), 's', 0, NULL },
1306         { BER_BVC("realm="), offsetof(slap_bindconf, sb_realm), 'b', 0, NULL },
1307         { BER_BVC("authcID="), offsetof(slap_bindconf, sb_authcId), 'b', 1, NULL },
1308         { BER_BVC("authzID="), offsetof(slap_bindconf, sb_authzId), 'b', 1, (slap_verbmasks *)authzNormalize },
1309         { BER_BVC("keepalive="), offsetof(slap_bindconf, sb_keepalive), 'x', 0, (slap_verbmasks *)slap_keepalive_parse },
1310 #ifdef HAVE_TLS
1311         { BER_BVC("starttls="), offsetof(slap_bindconf, sb_tls), 'i', 0, tlskey },
1312
1313         /* NOTE: replace "14" with the actual index
1314          * of the first TLS-related line */
1315 #define aux_TLS (bindkey+14)    /* beginning of TLS keywords */
1316
1317         { BER_BVC("tls_cert="), offsetof(slap_bindconf, sb_tls_cert), 's', 1, NULL },
1318         { BER_BVC("tls_key="), offsetof(slap_bindconf, sb_tls_key), 's', 1, NULL },
1319         { BER_BVC("tls_cacert="), offsetof(slap_bindconf, sb_tls_cacert), 's', 1, NULL },
1320         { BER_BVC("tls_cacertdir="), offsetof(slap_bindconf, sb_tls_cacertdir), 's', 1, NULL },
1321         { BER_BVC("tls_reqcert="), offsetof(slap_bindconf, sb_tls_reqcert), 's', 1, NULL },
1322         { BER_BVC("tls_cipher_suite="), offsetof(slap_bindconf, sb_tls_cipher_suite), 's', 1, NULL },
1323         { BER_BVC("tls_protocol_min="), offsetof(slap_bindconf, sb_tls_protocol_min), 's', 1, NULL },
1324 #ifdef HAVE_OPENSSL_CRL
1325         { BER_BVC("tls_crlcheck="), offsetof(slap_bindconf, sb_tls_crlcheck), 's', 1, NULL },
1326 #endif
1327 #endif
1328         { BER_BVNULL, 0, 0, 0, NULL }
1329 };
1330
1331 /*
1332  * 's': char *
1333  * 'b': struct berval; if !NULL, normalize using ((slap_mr_normalize_func *)aux)
1334  * 'i': int; if !NULL, compute using ((slap_verbmasks *)aux)
1335  * 'u': unsigned
1336  * 'I': long
1337  * 'U': unsigned long
1338  */
1339
1340 int
1341 slap_cf_aux_table_parse( const char *word, void *dst, slap_cf_aux_table *tab0, LDAP_CONST char *tabmsg )
1342 {
1343         int rc = SLAP_CONF_UNKNOWN;
1344         slap_cf_aux_table *tab;
1345
1346         for ( tab = tab0; !BER_BVISNULL( &tab->key ); tab++ ) {
1347                 if ( !strncasecmp( word, tab->key.bv_val, tab->key.bv_len ) ) {
1348                         char **cptr;
1349                         int *iptr, j;
1350                         unsigned *uptr;
1351                         long *lptr;
1352                         unsigned long *ulptr;
1353                         struct berval *bptr;
1354                         const char *val = word + tab->key.bv_len;
1355
1356                         switch ( tab->type ) {
1357                         case 's':
1358                                 cptr = (char **)((char *)dst + tab->off);
1359                                 *cptr = ch_strdup( val );
1360                                 rc = 0;
1361                                 break;
1362
1363                         case 'b':
1364                                 bptr = (struct berval *)((char *)dst + tab->off);
1365                                 if ( tab->aux != NULL ) {
1366                                         struct berval   dn;
1367                                         slap_mr_normalize_func *normalize = (slap_mr_normalize_func *)tab->aux;
1368
1369                                         ber_str2bv( val, 0, 0, &dn );
1370                                         rc = normalize( 0, NULL, NULL, &dn, bptr, NULL );
1371
1372                                 } else {
1373                                         ber_str2bv( val, 0, 1, bptr );
1374                                         rc = 0;
1375                                 }
1376                                 break;
1377
1378                         case 'i':
1379                                 iptr = (int *)((char *)dst + tab->off);
1380
1381                                 if ( tab->aux != NULL ) {
1382                                         slap_verbmasks *aux = (slap_verbmasks *)tab->aux;
1383
1384                                         assert( aux != NULL );
1385
1386                                         rc = 1;
1387                                         for ( j = 0; !BER_BVISNULL( &aux[j].word ); j++ ) {
1388                                                 if ( !strcasecmp( val, aux[j].word.bv_val ) ) {
1389                                                         *iptr = aux[j].mask;
1390                                                         rc = 0;
1391                                                         break;
1392                                                 }
1393                                         }
1394
1395                                 } else {
1396                                         rc = lutil_atoix( iptr, val, 0 );
1397                                 }
1398                                 break;
1399
1400                         case 'u':
1401                                 uptr = (unsigned *)((char *)dst + tab->off);
1402
1403                                 rc = lutil_atoux( uptr, val, 0 );
1404                                 break;
1405
1406                         case 'I':
1407                                 lptr = (long *)((char *)dst + tab->off);
1408
1409                                 rc = lutil_atolx( lptr, val, 0 );
1410                                 break;
1411
1412                         case 'U':
1413                                 ulptr = (unsigned long *)((char *)dst + tab->off);
1414
1415                                 rc = lutil_atoulx( ulptr, val, 0 );
1416                                 break;
1417
1418                         case 'x':
1419                                 if ( tab->aux != NULL ) {
1420                                         struct berval value;
1421                                         slap_cf_aux_table_parse_x *func = (slap_cf_aux_table_parse_x *)tab->aux;
1422
1423                                         ber_str2bv( val, 0, 1, &value );
1424
1425                                         rc = func( &value, (void *)((char *)dst + tab->off), tab, tabmsg, 0 );
1426
1427                                 } else {
1428                                         rc = 1;
1429                                 }
1430                                 break;
1431                         }
1432
1433                         if ( rc ) {
1434                                 Debug( LDAP_DEBUG_ANY, "invalid %s value %s\n",
1435                                         tabmsg, word, 0 );
1436                         }
1437                         
1438                         return rc;
1439                 }
1440         }
1441
1442         return rc;
1443 }
1444
1445 int
1446 slap_cf_aux_table_unparse( void *src, struct berval *bv, slap_cf_aux_table *tab0 )
1447 {
1448         char buf[AC_LINE_MAX], *ptr;
1449         slap_cf_aux_table *tab;
1450         struct berval tmp;
1451
1452         ptr = buf;
1453         for (tab = tab0; !BER_BVISNULL(&tab->key); tab++ ) {
1454                 char **cptr;
1455                 int *iptr, i;
1456                 unsigned *uptr;
1457                 long *lptr;
1458                 unsigned long *ulptr;
1459                 struct berval *bptr;
1460
1461                 cptr = (char **)((char *)src + tab->off);
1462
1463                 switch ( tab->type ) {
1464                 case 'b':
1465                         bptr = (struct berval *)((char *)src + tab->off);
1466                         cptr = &bptr->bv_val;
1467
1468                 case 's':
1469                         if ( *cptr ) {
1470                                 *ptr++ = ' ';
1471                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1472                                 if ( tab->quote ) *ptr++ = '"';
1473                                 ptr = lutil_strcopy( ptr, *cptr );
1474                                 if ( tab->quote ) *ptr++ = '"';
1475                         }
1476                         break;
1477
1478                 case 'i':
1479                         iptr = (int *)((char *)src + tab->off);
1480
1481                         if ( tab->aux != NULL ) {
1482                                 slap_verbmasks *aux = (slap_verbmasks *)tab->aux;
1483
1484                                 for ( i = 0; !BER_BVISNULL( &aux[i].word ); i++ ) {
1485                                         if ( *iptr == aux[i].mask ) {
1486                                                 *ptr++ = ' ';
1487                                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1488                                                 ptr = lutil_strcopy( ptr, aux[i].word.bv_val );
1489                                                 break;
1490                                         }
1491                                 }
1492
1493                         } else {
1494                                 *ptr++ = ' ';
1495                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1496                                 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%d", *iptr );
1497                         }
1498                         break;
1499
1500                 case 'u':
1501                         uptr = (unsigned *)((char *)src + tab->off);
1502                         *ptr++ = ' ';
1503                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1504                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%u", *uptr );
1505                         break;
1506
1507                 case 'I':
1508                         lptr = (long *)((char *)src + tab->off);
1509                         *ptr++ = ' ';
1510                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1511                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%ld", *lptr );
1512                         break;
1513
1514                 case 'U':
1515                         ulptr = (unsigned long *)((char *)src + tab->off);
1516                         *ptr++ = ' ';
1517                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1518                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%lu", *ulptr );
1519                         break;
1520
1521                 case 'x':
1522                         *ptr++ = ' ';
1523                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1524                         if ( tab->quote ) *ptr++ = '"';
1525                         if ( tab->aux != NULL ) {
1526                                 struct berval value;
1527                                 slap_cf_aux_table_parse_x *func = (slap_cf_aux_table_parse_x *)tab->aux;
1528                                 int rc;
1529
1530                                 value.bv_val = ptr;
1531                                 value.bv_len = buf + sizeof( buf ) - ptr;
1532
1533                                 rc = func( &value, (void *)((char *)src + tab->off), tab, "(unparse)", 1 );
1534                                 if ( rc == 0 ) {
1535                                         ptr += value.bv_len;
1536                                 }
1537                         }
1538                         if ( tab->quote ) *ptr++ = '"';
1539                         break;
1540
1541                 default:
1542                         assert( 0 );
1543                 }
1544         }
1545         tmp.bv_val = buf;
1546         tmp.bv_len = ptr - buf;
1547         ber_dupbv( bv, &tmp );
1548         return 0;
1549 }
1550
1551 int
1552 slap_tls_get_config( LDAP *ld, int opt, char **val )
1553 {
1554 #ifdef HAVE_TLS
1555         slap_verbmasks *keys;
1556         int i, ival;
1557
1558         *val = NULL;
1559         switch( opt ) {
1560         case LDAP_OPT_X_TLS_CRLCHECK:
1561                 keys = crlkeys;
1562                 break;
1563         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1564                 keys = vfykeys;
1565                 break;
1566         case LDAP_OPT_X_TLS_PROTOCOL_MIN: {
1567                 char buf[8];
1568                 ldap_pvt_tls_get_option( ld, opt, &ival );
1569                 snprintf( buf, sizeof( buf ), "%d.%d",
1570                         ( ival >> 8 ) & 0xff, ival & 0xff );
1571                 *val = ch_strdup( buf );
1572                 return 0;
1573                 }
1574         default:
1575                 return -1;
1576         }
1577         ldap_pvt_tls_get_option( ld, opt, &ival );
1578         for (i=0; !BER_BVISNULL(&keys[i].word); i++) {
1579                 if (keys[i].mask == ival) {
1580                         *val = ch_strdup( keys[i].word.bv_val );
1581                         return 0;
1582                 }
1583         }
1584 #endif
1585         return -1;
1586 }
1587
1588 int
1589 bindconf_tls_parse( const char *word, slap_bindconf *bc )
1590 {
1591 #ifdef HAVE_TLS
1592         if ( slap_cf_aux_table_parse( word, bc, aux_TLS, "tls config" ) == 0 ) {
1593                 bc->sb_tls_do_init = 1;
1594                 return 0;
1595         }
1596 #endif
1597         return -1;
1598 }
1599
1600 int
1601 bindconf_tls_unparse( slap_bindconf *bc, struct berval *bv )
1602 {
1603 #ifdef HAVE_TLS
1604         return slap_cf_aux_table_unparse( bc, bv, aux_TLS );
1605 #endif
1606         return -1;
1607 }
1608
1609 int
1610 bindconf_parse( const char *word, slap_bindconf *bc )
1611 {
1612 #ifdef HAVE_TLS
1613         /* Detect TLS config changes explicitly */
1614         if ( bindconf_tls_parse( word, bc ) == 0 ) {
1615                 return 0;
1616         }
1617 #endif
1618         return slap_cf_aux_table_parse( word, bc, bindkey, "bind config" );
1619 }
1620
1621 int
1622 bindconf_unparse( slap_bindconf *bc, struct berval *bv )
1623 {
1624         return slap_cf_aux_table_unparse( bc, bv, bindkey );
1625 }
1626
1627 void bindconf_free( slap_bindconf *bc ) {
1628         if ( !BER_BVISNULL( &bc->sb_uri ) ) {
1629                 ch_free( bc->sb_uri.bv_val );
1630                 BER_BVZERO( &bc->sb_uri );
1631         }
1632         if ( !BER_BVISNULL( &bc->sb_binddn ) ) {
1633                 ch_free( bc->sb_binddn.bv_val );
1634                 BER_BVZERO( &bc->sb_binddn );
1635         }
1636         if ( !BER_BVISNULL( &bc->sb_cred ) ) {
1637                 ch_free( bc->sb_cred.bv_val );
1638                 BER_BVZERO( &bc->sb_cred );
1639         }
1640         if ( !BER_BVISNULL( &bc->sb_saslmech ) ) {
1641                 ch_free( bc->sb_saslmech.bv_val );
1642                 BER_BVZERO( &bc->sb_saslmech );
1643         }
1644         if ( bc->sb_secprops ) {
1645                 ch_free( bc->sb_secprops );
1646                 bc->sb_secprops = NULL;
1647         }
1648         if ( !BER_BVISNULL( &bc->sb_realm ) ) {
1649                 ch_free( bc->sb_realm.bv_val );
1650                 BER_BVZERO( &bc->sb_realm );
1651         }
1652         if ( !BER_BVISNULL( &bc->sb_authcId ) ) {
1653                 ch_free( bc->sb_authcId.bv_val );
1654                 BER_BVZERO( &bc->sb_authcId );
1655         }
1656         if ( !BER_BVISNULL( &bc->sb_authzId ) ) {
1657                 ch_free( bc->sb_authzId.bv_val );
1658                 BER_BVZERO( &bc->sb_authzId );
1659         }
1660 #ifdef HAVE_TLS
1661         if ( bc->sb_tls_cert ) {
1662                 ch_free( bc->sb_tls_cert );
1663                 bc->sb_tls_cert = NULL;
1664         }
1665         if ( bc->sb_tls_key ) {
1666                 ch_free( bc->sb_tls_key );
1667                 bc->sb_tls_key = NULL;
1668         }
1669         if ( bc->sb_tls_cacert ) {
1670                 ch_free( bc->sb_tls_cacert );
1671                 bc->sb_tls_cacert = NULL;
1672         }
1673         if ( bc->sb_tls_cacertdir ) {
1674                 ch_free( bc->sb_tls_cacertdir );
1675                 bc->sb_tls_cacertdir = NULL;
1676         }
1677         if ( bc->sb_tls_reqcert ) {
1678                 ch_free( bc->sb_tls_reqcert );
1679                 bc->sb_tls_reqcert = NULL;
1680         }
1681         if ( bc->sb_tls_cipher_suite ) {
1682                 ch_free( bc->sb_tls_cipher_suite );
1683                 bc->sb_tls_cipher_suite = NULL;
1684         }
1685         if ( bc->sb_tls_protocol_min ) {
1686                 ch_free( bc->sb_tls_protocol_min );
1687                 bc->sb_tls_protocol_min = NULL;
1688         }
1689 #ifdef HAVE_OPENSSL_CRL
1690         if ( bc->sb_tls_crlcheck ) {
1691                 ch_free( bc->sb_tls_crlcheck );
1692                 bc->sb_tls_crlcheck = NULL;
1693         }
1694 #endif
1695 #endif
1696 }
1697
1698 void
1699 bindconf_tls_defaults( slap_bindconf *bc )
1700 {
1701 #ifdef HAVE_TLS
1702         if ( bc->sb_tls_do_init ) {
1703                 if ( !bc->sb_tls_cacert )
1704                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CACERTFILE,
1705                                 &bc->sb_tls_cacert );
1706                 if ( !bc->sb_tls_cacertdir )
1707                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CACERTDIR,
1708                                 &bc->sb_tls_cacertdir );
1709                 if ( !bc->sb_tls_cert )
1710                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CERTFILE,
1711                                 &bc->sb_tls_cert );
1712                 if ( !bc->sb_tls_key )
1713                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_KEYFILE,
1714                                 &bc->sb_tls_key );
1715                 if ( !bc->sb_tls_cipher_suite )
1716                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CIPHER_SUITE,
1717                                 &bc->sb_tls_cipher_suite );
1718                 if ( !bc->sb_tls_reqcert )
1719                         bc->sb_tls_reqcert = ch_strdup("demand");
1720 #ifdef HAVE_OPENSSL_CRL
1721                 if ( !bc->sb_tls_crlcheck )
1722                         slap_tls_get_config( slap_tls_ld, LDAP_OPT_X_TLS_CRLCHECK,
1723                                 &bc->sb_tls_crlcheck );
1724 #endif
1725         }
1726 #endif
1727 }
1728
1729 #ifdef HAVE_TLS
1730 static struct {
1731         const char *key;
1732         size_t offset;
1733         int opt;
1734 } bindtlsopts[] = {
1735         { "tls_cert", offsetof(slap_bindconf, sb_tls_cert), LDAP_OPT_X_TLS_CERTFILE },
1736         { "tls_key", offsetof(slap_bindconf, sb_tls_key), LDAP_OPT_X_TLS_KEYFILE },
1737         { "tls_cacert", offsetof(slap_bindconf, sb_tls_cacert), LDAP_OPT_X_TLS_CACERTFILE },
1738         { "tls_cacertdir", offsetof(slap_bindconf, sb_tls_cacertdir), LDAP_OPT_X_TLS_CACERTDIR },
1739         { "tls_cipher_suite", offsetof(slap_bindconf, sb_tls_cipher_suite), LDAP_OPT_X_TLS_CIPHER_SUITE },
1740         { "tls_protocol_min", offsetof(slap_bindconf, sb_tls_protocol_min), LDAP_OPT_X_TLS_PROTOCOL_MIN },
1741         {0, 0}
1742 };
1743
1744 int bindconf_tls_set( slap_bindconf *bc, LDAP *ld )
1745 {
1746         int i, rc, newctx = 0, res = 0;
1747         char *ptr = (char *)bc, **word;
1748
1749         bc->sb_tls_do_init = 0;
1750
1751         for (i=0; bindtlsopts[i].opt; i++) {
1752                 word = (char **)(ptr + bindtlsopts[i].offset);
1753                 if ( *word ) {
1754                         rc = ldap_set_option( ld, bindtlsopts[i].opt, *word );
1755                         if ( rc ) {
1756                                 Debug( LDAP_DEBUG_ANY,
1757                                         "bindconf_tls_set: failed to set %s to %s\n",
1758                                                 bindtlsopts[i].key, *word, 0 );
1759                                 res = -1;
1760                         } else
1761                                 newctx = 1;
1762                 }
1763         }
1764         if ( bc->sb_tls_reqcert ) {
1765                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_REQUIRE_CERT,
1766                         bc->sb_tls_reqcert );
1767                 if ( rc ) {
1768                         Debug( LDAP_DEBUG_ANY,
1769                                 "bindconf_tls_set: failed to set tls_reqcert to %s\n",
1770                                         bc->sb_tls_reqcert, 0, 0 );
1771                         res = -1;
1772                 } else
1773                         newctx = 1;
1774         }
1775         if ( bc->sb_tls_protocol_min ) {
1776                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_PROTOCOL_MIN,
1777                         bc->sb_tls_protocol_min );
1778                 if ( rc ) {
1779                         Debug( LDAP_DEBUG_ANY,
1780                                 "bindconf_tls_set: failed to set tls_protocol_min to %s\n",
1781                                         bc->sb_tls_protocol_min, 0, 0 );
1782                         res = -1;
1783                 } else
1784                         newctx = 1;
1785         }
1786 #ifdef HAVE_OPENSSL_CRL
1787         if ( bc->sb_tls_crlcheck ) {
1788                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_CRLCHECK,
1789                         bc->sb_tls_crlcheck );
1790                 if ( rc ) {
1791                         Debug( LDAP_DEBUG_ANY,
1792                                 "bindconf_tls_set: failed to set tls_crlcheck to %s\n",
1793                                         bc->sb_tls_crlcheck, 0, 0 );
1794                         res = -1;
1795                 } else
1796                         newctx = 1;
1797         }
1798 #endif
1799         if ( newctx ) {
1800                 int opt = 0;
1801
1802                 if ( bc->sb_tls_ctx ) {
1803                         ldap_pvt_tls_ctx_free( bc->sb_tls_ctx );
1804                         bc->sb_tls_ctx = NULL;
1805                 }
1806                 rc = ldap_set_option( ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
1807                 if ( rc )
1808                         res = rc;
1809                 else
1810                         ldap_get_option( ld, LDAP_OPT_X_TLS_CTX, &bc->sb_tls_ctx );
1811         }
1812         
1813         return res;
1814 }
1815 #endif
1816
1817 /*
1818  * connect to a client using the bindconf data
1819  * note: should move "version" into bindconf...
1820  */
1821 int
1822 slap_client_connect( LDAP **ldp, slap_bindconf *sb )
1823 {
1824         LDAP            *ld = NULL;
1825         int             rc;
1826         struct timeval tv;
1827
1828         /* Init connection to master */
1829         rc = ldap_initialize( &ld, sb->sb_uri.bv_val );
1830         if ( rc != LDAP_SUCCESS ) {
1831                 Debug( LDAP_DEBUG_ANY,
1832                         "slap_client_connect: "
1833                         "ldap_initialize(%s) failed (%d)\n",
1834                         sb->sb_uri.bv_val, rc, 0 );
1835                 return rc;
1836         }
1837
1838         if ( sb->sb_version != 0 ) {
1839                 ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
1840                         (const void *)&sb->sb_version );
1841         }
1842
1843         if ( sb->sb_timeout_api ) {
1844                 tv.tv_sec = sb->sb_timeout_api;
1845                 tv.tv_usec = 0;
1846                 ldap_set_option( ld, LDAP_OPT_TIMEOUT, &tv );
1847         }
1848
1849         if ( sb->sb_timeout_net ) {
1850                 tv.tv_sec = sb->sb_timeout_net;
1851                 tv.tv_usec = 0;
1852                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, &tv );
1853         }
1854
1855         if ( sb->sb_keepalive.sk_idle ) {
1856                 ldap_set_option( ld, LDAP_OPT_X_KEEPALIVE_IDLE, &sb->sb_keepalive.sk_idle );
1857         }
1858
1859         if ( sb->sb_keepalive.sk_probes ) {
1860                 ldap_set_option( ld, LDAP_OPT_X_KEEPALIVE_PROBES, &sb->sb_keepalive.sk_probes );
1861         }
1862
1863         if ( sb->sb_keepalive.sk_interval ) {
1864                 ldap_set_option( ld, LDAP_OPT_X_KEEPALIVE_INTERVAL, &sb->sb_keepalive.sk_interval );
1865         }
1866
1867 #ifdef HAVE_TLS
1868         if ( sb->sb_tls_do_init ) {
1869                 rc = bindconf_tls_set( sb, ld );
1870
1871         } else if ( sb->sb_tls_ctx ) {
1872                 rc = ldap_set_option( ld, LDAP_OPT_X_TLS_CTX,
1873                         sb->sb_tls_ctx );
1874         }
1875
1876         if ( rc ) {
1877                 Debug( LDAP_DEBUG_ANY,
1878                         "slap_client_connect: "
1879                         "URI=%s TLS context initialization failed (%d)\n",
1880                         sb->sb_uri.bv_val, rc, 0 );
1881                 return rc;
1882         }
1883 #endif
1884
1885         /* Bind */
1886         if ( sb->sb_tls ) {
1887                 rc = ldap_start_tls_s( ld, NULL, NULL );
1888                 if ( rc != LDAP_SUCCESS ) {
1889                         Debug( LDAP_DEBUG_ANY,
1890                                 "slap_client_connect: URI=%s "
1891                                 "%s, ldap_start_tls failed (%d)\n",
1892                                 sb->sb_uri.bv_val,
1893                                 sb->sb_tls == SB_TLS_CRITICAL ?
1894                                         "Error" : "Warning",
1895                                 rc );
1896                         if ( sb->sb_tls == SB_TLS_CRITICAL ) {
1897                                 goto done;
1898                         }
1899                 }
1900         }
1901
1902         if ( sb->sb_method == LDAP_AUTH_SASL ) {
1903 #ifdef HAVE_CYRUS_SASL
1904                 void *defaults;
1905
1906                 if ( sb->sb_secprops != NULL ) {
1907                         rc = ldap_set_option( ld,
1908                                 LDAP_OPT_X_SASL_SECPROPS, sb->sb_secprops);
1909
1910                         if( rc != LDAP_OPT_SUCCESS ) {
1911                                 Debug( LDAP_DEBUG_ANY,
1912                                         "slap_client_connect: "
1913                                         "error, ldap_set_option "
1914                                         "(%s,SECPROPS,\"%s\") failed!\n",
1915                                         sb->sb_uri.bv_val, sb->sb_secprops, 0 );
1916                                 goto done;
1917                         }
1918                 }
1919
1920                 defaults = lutil_sasl_defaults( ld,
1921                         sb->sb_saslmech.bv_val,
1922                         sb->sb_realm.bv_val,
1923                         sb->sb_authcId.bv_val,
1924                         sb->sb_cred.bv_val,
1925                         sb->sb_authzId.bv_val );
1926                 if ( defaults == NULL ) {
1927                         rc = LDAP_OTHER;
1928                         goto done;
1929                 }
1930
1931                 rc = ldap_sasl_interactive_bind_s( ld,
1932                                 sb->sb_binddn.bv_val,
1933                                 sb->sb_saslmech.bv_val,
1934                                 NULL, NULL,
1935                                 LDAP_SASL_QUIET,
1936                                 lutil_sasl_interact,
1937                                 defaults );
1938
1939                 lutil_sasl_freedefs( defaults );
1940
1941                 /* FIXME: different error behaviors according to
1942                  *      1) return code
1943                  *      2) on err policy : exit, retry, backoff ...
1944                  */
1945                 if ( rc != LDAP_SUCCESS ) {
1946                         static struct berval bv_GSSAPI = BER_BVC( "GSSAPI" );
1947
1948                         Debug( LDAP_DEBUG_ANY, "slap_client_connect: URI=%s "
1949                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
1950                                 sb->sb_uri.bv_val, rc, 0 );
1951
1952                         /* FIXME (see above comment) */
1953                         /* if Kerberos credentials cache is not active, retry */
1954                         if ( ber_bvcmp( &sb->sb_saslmech, &bv_GSSAPI ) == 0 &&
1955                                 rc == LDAP_LOCAL_ERROR )
1956                         {
1957                                 rc = LDAP_SERVER_DOWN;
1958                         }
1959
1960                         goto done;
1961                 }
1962 #else /* HAVE_CYRUS_SASL */
1963                 /* Should never get here, we trapped this at config time */
1964                 assert(0);
1965                 Debug( LDAP_DEBUG_SYNC, "not compiled with SASL support\n", 0, 0, 0 );
1966                 rc = LDAP_OTHER;
1967                 goto done;
1968 #endif
1969
1970         } else if ( sb->sb_method == LDAP_AUTH_SIMPLE ) {
1971                 rc = ldap_sasl_bind_s( ld,
1972                         sb->sb_binddn.bv_val, LDAP_SASL_SIMPLE,
1973                         &sb->sb_cred, NULL, NULL, NULL );
1974                 if ( rc != LDAP_SUCCESS ) {
1975                         Debug( LDAP_DEBUG_ANY, "slap_client_connect: "
1976                                 "URI=%s DN=\"%s\" "
1977                                 "ldap_sasl_bind_s failed (%d)\n",
1978                                 sb->sb_uri.bv_val, sb->sb_binddn.bv_val, rc );
1979                         goto done;
1980                 }
1981         }
1982
1983 done:;
1984         if ( rc ) {
1985                 if ( ld ) {
1986                         ldap_unbind_ext( ld, NULL, NULL );
1987                         *ldp = NULL;
1988                 }
1989
1990         } else {
1991                 *ldp = ld;
1992         }
1993
1994         return rc;
1995 }
1996
1997 /* -------------------------------------- */
1998
1999
2000 static char *
2001 strtok_quote( char *line, char *sep, char **quote_ptr )
2002 {
2003         int             inquote;
2004         char            *tmp;
2005         static char     *next;
2006
2007         *quote_ptr = NULL;
2008         if ( line != NULL ) {
2009                 next = line;
2010         }
2011         while ( *next && strchr( sep, *next ) ) {
2012                 next++;
2013         }
2014
2015         if ( *next == '\0' ) {
2016                 next = NULL;
2017                 return( NULL );
2018         }
2019         tmp = next;
2020
2021         for ( inquote = 0; *next; ) {
2022                 switch ( *next ) {
2023                 case '"':
2024                         if ( inquote ) {
2025                                 inquote = 0;
2026                         } else {
2027                                 inquote = 1;
2028                         }
2029                         AC_MEMCPY( next, next + 1, strlen( next + 1 ) + 1 );
2030                         break;
2031
2032                 case '\\':
2033                         if ( next[1] )
2034                                 AC_MEMCPY( next,
2035                                             next + 1, strlen( next + 1 ) + 1 );
2036                         next++;         /* dont parse the escaped character */
2037                         break;
2038
2039                 default:
2040                         if ( ! inquote ) {
2041                                 if ( strchr( sep, *next ) != NULL ) {
2042                                         *quote_ptr = next;
2043                                         *next++ = '\0';
2044                                         return( tmp );
2045                                 }
2046                         }
2047                         next++;
2048                         break;
2049                 }
2050         }
2051
2052         return( tmp );
2053 }
2054
2055 static char     buf[AC_LINE_MAX];
2056 static char     *line;
2057 static size_t lmax, lcur;
2058
2059 #define CATLINE( buf ) \
2060         do { \
2061                 size_t len = strlen( buf ); \
2062                 while ( lcur + len + 1 > lmax ) { \
2063                         lmax += AC_LINE_MAX; \
2064                         line = (char *) ch_realloc( line, lmax ); \
2065                 } \
2066                 strcpy( line + lcur, buf ); \
2067                 lcur += len; \
2068         } while( 0 )
2069
2070 static void
2071 fp_getline_init(ConfigArgs *c) {
2072         c->lineno = -1;
2073         buf[0] = '\0';
2074 }
2075
2076 static int
2077 fp_getline( FILE *fp, ConfigArgs *c )
2078 {
2079         char    *p;
2080
2081         lcur = 0;
2082         CATLINE(buf);
2083         c->lineno++;
2084
2085         /* avoid stack of bufs */
2086         if ( strncasecmp( line, "include", STRLENOF( "include" ) ) == 0 ) {
2087                 buf[0] = '\0';
2088                 c->line = line;
2089                 return(1);
2090         }
2091
2092         while ( fgets( buf, sizeof( buf ), fp ) ) {
2093                 p = strchr( buf, '\n' );
2094                 if ( p ) {
2095                         if ( p > buf && p[-1] == '\r' ) {
2096                                 --p;
2097                         }
2098                         *p = '\0';
2099                 }
2100                 /* XXX ugly */
2101                 c->line = line;
2102                 if ( line[0]
2103                                 && ( p = line + strlen( line ) - 1 )[0] == '\\'
2104                                 && p[-1] != '\\' )
2105                 {
2106                         p[0] = '\0';
2107                         lcur--;
2108                         
2109                 } else {
2110                         if ( !isspace( (unsigned char)buf[0] ) ) {
2111                                 return(1);
2112                         }
2113                         buf[0] = ' ';
2114                 }
2115                 CATLINE(buf);
2116                 c->lineno++;
2117         }
2118
2119         buf[0] = '\0';
2120         c->line = line;
2121         return(line[0] ? 1 : 0);
2122 }
2123
2124 int
2125 config_fp_parse_line(ConfigArgs *c)
2126 {
2127         char *token;
2128         static char *const hide[] = {
2129                 "rootpw", "replica", "syncrepl",  /* in slapd */
2130                 "acl-bind", "acl-method", "idassert-bind",  /* in back-ldap */
2131                 "acl-passwd", "bindpw",  /* in back-<ldap/meta> */
2132                 "pseudorootpw",  /* in back-meta */
2133                 "dbpasswd",  /* in back-sql */
2134                 NULL
2135         };
2136         char *quote_ptr;
2137         int i = (int)(sizeof(hide)/sizeof(hide[0])) - 1;
2138
2139         c->tline = ch_strdup(c->line);
2140         token = strtok_quote(c->tline, " \t", &quote_ptr);
2141
2142         if(token) for(i = 0; hide[i]; i++) if(!strcasecmp(token, hide[i])) break;
2143         if(quote_ptr) *quote_ptr = ' ';
2144         Debug(LDAP_DEBUG_CONFIG, "line %d (%s%s)\n", c->lineno,
2145                 hide[i] ? hide[i] : c->line, hide[i] ? " ***" : "");
2146         if(quote_ptr) *quote_ptr = '\0';
2147
2148         for(;; token = strtok_quote(NULL, " \t", &quote_ptr)) {
2149                 if(c->argc >= c->argv_size) {
2150                         char **tmp;
2151                         tmp = ch_realloc(c->argv, (c->argv_size + ARGS_STEP) * sizeof(*c->argv));
2152                         if(!tmp) {
2153                                 Debug(LDAP_DEBUG_ANY, "line %d: out of memory\n", c->lineno, 0, 0);
2154                                 return -1;
2155                         }
2156                         c->argv = tmp;
2157                         c->argv_size += ARGS_STEP;
2158                 }
2159                 if(token == NULL)
2160                         break;
2161                 c->argv[c->argc++] = token;
2162         }
2163         c->argv[c->argc] = NULL;
2164         return(0);
2165 }
2166
2167 void
2168 config_destroy( )
2169 {
2170         ucdata_unload( UCDATA_ALL );
2171         if ( frontendDB ) {
2172                 /* NOTE: in case of early exit, frontendDB can be NULL */
2173                 if ( frontendDB->be_schemandn.bv_val )
2174                         free( frontendDB->be_schemandn.bv_val );
2175                 if ( frontendDB->be_schemadn.bv_val )
2176                         free( frontendDB->be_schemadn.bv_val );
2177                 if ( frontendDB->be_acl )
2178                         acl_destroy( frontendDB->be_acl );
2179         }
2180         free( line );
2181         if ( slapd_args_file )
2182                 free ( slapd_args_file );
2183         if ( slapd_pid_file )
2184                 free ( slapd_pid_file );
2185         if ( default_passwd_hash )
2186                 ldap_charray_free( default_passwd_hash );
2187 }
2188
2189 char **
2190 slap_str2clist( char ***out, char *in, const char *brkstr )
2191 {
2192         char    *str;
2193         char    *s;
2194         char    *lasts;
2195         int     i, j;
2196         char    **new;
2197
2198         /* find last element in list */
2199         for (i = 0; *out && (*out)[i]; i++);
2200
2201         /* protect the input string from strtok */
2202         str = ch_strdup( in );
2203
2204         if ( *str == '\0' ) {
2205                 free( str );
2206                 return( *out );
2207         }
2208
2209         /* Count words in string */
2210         j=1;
2211         for ( s = str; *s; s++ ) {
2212                 if ( strchr( brkstr, *s ) != NULL ) {
2213                         j++;
2214                 }
2215         }
2216
2217         *out = ch_realloc( *out, ( i + j + 1 ) * sizeof( char * ) );
2218         new = *out + i;
2219         for ( s = ldap_pvt_strtok( str, brkstr, &lasts );
2220                 s != NULL;
2221                 s = ldap_pvt_strtok( NULL, brkstr, &lasts ) )
2222         {
2223                 *new = ch_strdup( s );
2224                 new++;
2225         }
2226
2227         *new = NULL;
2228         free( str );
2229         return( *out );
2230 }
2231
2232 int config_generic_wrapper( Backend *be, const char *fname, int lineno,
2233         int argc, char **argv )
2234 {
2235         ConfigArgs c = { 0 };
2236         ConfigTable *ct;
2237         int rc;
2238
2239         c.be = be;
2240         c.fname = fname;
2241         c.lineno = lineno;
2242         c.argc = argc;
2243         c.argv = argv;
2244         c.valx = -1;
2245         c.line = line;
2246         c.op = SLAP_CONFIG_ADD;
2247         snprintf( c.log, sizeof( c.log ), "%s: line %d", fname, lineno );
2248
2249         rc = SLAP_CONF_UNKNOWN;
2250         ct = config_find_keyword( be->be_cf_ocs->co_table, &c );
2251         if ( ct ) {
2252                 c.table = be->be_cf_ocs->co_type;
2253                 rc = config_add_vals( ct, &c );
2254         }
2255         return rc;
2256 }
2257
2258 /* See if the given URL (in plain and parsed form) matches
2259  * any of the server's listener addresses. Return matching
2260  * Listener or NULL for no match.
2261  */
2262 Listener *config_check_my_url( const char *url, LDAPURLDesc *lud )
2263 {
2264         Listener **l = slapd_get_listeners();
2265         int i, isMe;
2266
2267         /* Try a straight compare with Listener strings */
2268         for ( i=0; l && l[i]; i++ ) {
2269                 if ( !strcasecmp( url, l[i]->sl_url.bv_val )) {
2270                         return l[i];
2271                 }
2272         }
2273
2274         isMe = 0;
2275         /* If hostname is empty, or is localhost, or matches
2276          * our hostname, this url refers to this host.
2277          * Compare it against listeners and ports.
2278          */
2279         if ( !lud->lud_host || !lud->lud_host[0] ||
2280                 !strncasecmp("localhost", lud->lud_host,
2281                         STRLENOF("localhost")) ||
2282                 !strcasecmp( global_host, lud->lud_host )) {
2283
2284                 for ( i=0; l && l[i]; i++ ) {
2285                         LDAPURLDesc *lu2;
2286                         ldap_url_parse( l[i]->sl_url.bv_val, &lu2 );
2287                         do {
2288                                 if ( strcasecmp( lud->lud_scheme,
2289                                         lu2->lud_scheme ))
2290                                         break;
2291                                 if ( lud->lud_port != lu2->lud_port )
2292                                         break;
2293                                 /* Listener on ANY address */
2294                                 if ( !lu2->lud_host || !lu2->lud_host[0] ) {
2295                                         isMe = 1;
2296                                         break;
2297                                 }
2298                                 /* URL on ANY address */
2299                                 if ( !lud->lud_host || !lud->lud_host[0] ) {
2300                                         isMe = 1;
2301                                         break;
2302                                 }
2303                                 /* Listener has specific host, must
2304                                  * match it
2305                                  */
2306                                 if ( !strcasecmp( lud->lud_host,
2307                                         lu2->lud_host )) {
2308                                         isMe = 1;
2309                                         break;
2310                                 }
2311                         } while(0);
2312                         ldap_free_urldesc( lu2 );
2313                         if ( isMe ) {
2314                                 return l[i];
2315                         }
2316                 }
2317         }
2318         return NULL;
2319 }