]> git.sur5r.net Git - openldap/blob - servers/slapd/config.c
ITS#6342 include <ac/unistd.h>
[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 < j ) {
307                         larg = larg ? larg : (barg ? 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->op = LDAP_MOD_DELETE;
418                 c->type = cf->arg_type & ARGS_USERLAND;
419                 rc = (*((ConfigDriver*)cf->arg_item))(c);
420         }
421         return rc;
422 }
423
424 int
425 config_get_vals(ConfigTable *cf, ConfigArgs *c)
426 {
427         int rc = 0;
428         struct berval bv;
429         void *ptr;
430
431         if ( cf->arg_type & ARG_IGNORED ) {
432                 return 1;
433         }
434
435         memset(&c->values, 0, sizeof(c->values));
436         c->rvalue_vals = NULL;
437         c->rvalue_nvals = NULL;
438         c->op = SLAP_CONFIG_EMIT;
439         c->type = cf->arg_type & ARGS_USERLAND;
440
441         if ( cf->arg_type & ARG_MAGIC ) {
442                 rc = (*((ConfigDriver*)cf->arg_item))(c);
443                 if ( rc ) return rc;
444         } else {
445                 if ( cf->arg_type & ARG_OFFSET ) {
446                         if (c->be && c->table == Cft_Database)
447                                 ptr = c->be->be_private;
448                         else if ( c->bi )
449                                 ptr = c->bi->bi_private;
450                         else
451                                 return 1;
452                         ptr = (void *)((char *)ptr + (long)cf->arg_item);
453                 } else {
454                         ptr = cf->arg_item;
455                 }
456                 
457                 switch(cf->arg_type & ARGS_TYPES) {
458                 case ARG_ON_OFF:
459                 case ARG_INT:   c->value_int = *(int *)ptr; break;
460                 case ARG_UINT:  c->value_uint = *(unsigned *)ptr; break;
461                 case ARG_LONG:  c->value_long = *(long *)ptr; break;
462                 case ARG_ULONG: c->value_ulong = *(unsigned long *)ptr; break;
463                 case ARG_BER_LEN_T:     c->value_ber_t = *(ber_len_t *)ptr; break;
464                 case ARG_STRING:
465                         if ( *(char **)ptr )
466                                 c->value_string = ch_strdup(*(char **)ptr);
467                         break;
468                 case ARG_BERVAL:
469                         ber_dupbv( &c->value_bv, (struct berval *)ptr ); break;
470                 case ARG_ATDESC:
471                         c->value_ad = *(AttributeDescription **)ptr; break;
472                 }
473         }
474         if ( cf->arg_type & ARGS_TYPES) {
475                 bv.bv_len = 0;
476                 bv.bv_val = c->log;
477                 switch(cf->arg_type & ARGS_TYPES) {
478                 case ARG_INT: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%d", c->value_int); break;
479                 case ARG_UINT: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%u", c->value_uint); break;
480                 case ARG_LONG: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%ld", c->value_long); break;
481                 case ARG_ULONG: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%lu", c->value_ulong); break;
482                 case ARG_BER_LEN_T: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%ld", c->value_ber_t); break;
483                 case ARG_ON_OFF: bv.bv_len = snprintf(bv.bv_val, sizeof( c->log ), "%s",
484                         c->value_int ? "TRUE" : "FALSE"); break;
485                 case ARG_STRING:
486                         if ( c->value_string && c->value_string[0]) {
487                                 ber_str2bv( c->value_string, 0, 0, &bv);
488                         } else {
489                                 return 1;
490                         }
491                         break;
492                 case ARG_BERVAL:
493                         if ( !BER_BVISEMPTY( &c->value_bv )) {
494                                 bv = c->value_bv;
495                         } else {
496                                 return 1;
497                         }
498                         break;
499                 case ARG_ATDESC:
500                         if ( c->value_ad ) {
501                                 bv = c->value_ad->ad_cname;
502                         } else {
503                                 return 1;
504                         }
505                         break;
506                 default:
507                         bv.bv_val = NULL;
508                         break;
509                 }
510                 if (bv.bv_val == c->log && bv.bv_len >= sizeof( c->log ) ) {
511                         return 1;
512                 }
513                 if (( cf->arg_type & ARGS_TYPES ) == ARG_STRING ) {
514                         ber_bvarray_add(&c->rvalue_vals, &bv);
515                 } else if ( !BER_BVISNULL( &bv ) ) {
516                         value_add_one(&c->rvalue_vals, &bv);
517                 }
518                 /* else: maybe c->rvalue_vals already set? */
519         }
520         return rc;
521 }
522
523 int
524 init_config_attrs(ConfigTable *ct) {
525         int i, code;
526
527         for (i=0; ct[i].name; i++ ) {
528                 if ( !ct[i].attribute ) continue;
529                 code = register_at( ct[i].attribute, &ct[i].ad, 1 );
530                 if ( code ) {
531                         fprintf( stderr, "init_config_attrs: register_at failed\n" );
532                         return code;
533                 }
534         }
535
536         return 0;
537 }
538
539 int
540 init_config_ocs( ConfigOCs *ocs ) {
541         int i, code;
542
543         for (i=0;ocs[i].co_def;i++) {
544                 code = register_oc( ocs[i].co_def, &ocs[i].co_oc, 1 );
545                 if ( code ) {
546                         fprintf( stderr, "init_config_ocs: register_oc failed\n" );
547                         return code;
548                 }
549         }
550         return 0;
551 }
552
553 /* Split an LDIF line into space-separated tokens. Words may be grouped
554  * by quotes. A quoted string may begin in the middle of a word, but must
555  * end at the end of the word (be followed by whitespace or EOS). Any other
556  * quotes are passed through unchanged. All other characters are passed
557  * through unchanged.
558  */
559 static char *
560 strtok_quote_ldif( char **line )
561 {
562         char *beg, *ptr, *quote=NULL;
563         int inquote=0;
564
565         ptr = *line;
566
567         if ( !ptr || !*ptr )
568                 return NULL;
569
570         while( isspace( (unsigned char) *ptr )) ptr++;
571
572         if ( *ptr == '"' ) {
573                 inquote = 1;
574                 ptr++;
575         }
576
577         beg = ptr;
578
579         for (;*ptr;ptr++) {
580                 if ( *ptr == '"' ) {
581                         if ( inquote && ( !ptr[1] || isspace((unsigned char) ptr[1]))) {
582                                 *ptr++ = '\0';
583                                 break;
584                         }
585                         inquote = 1;
586                         quote = ptr;
587                         continue;
588                 }
589                 if ( inquote )
590                         continue;
591                 if ( isspace( (unsigned char) *ptr )) {
592                         *ptr++ = '\0';
593                         break;
594                 }
595         }
596         if ( quote ) {
597                 while ( quote < ptr ) {
598                         *quote = quote[1];
599                         quote++;
600                 }
601         }
602         if ( !*ptr ) {
603                 *line = NULL;
604         } else {
605                 while ( isspace( (unsigned char) *ptr )) ptr++;
606                 *line = ptr;
607         }
608         return beg;
609 }
610
611 static void
612 config_parse_ldif( ConfigArgs *c )
613 {
614         char *next;
615         c->tline = ch_strdup(c->line);
616         next = c->tline;
617
618         while ((c->argv[c->argc] = strtok_quote_ldif( &next )) != NULL) {
619                 c->argc++;
620                 if ( c->argc >= c->argv_size ) {
621                         char **tmp = ch_realloc( c->argv, (c->argv_size + ARGS_STEP) *
622                                 sizeof( *c->argv ));
623                         c->argv = tmp;
624                         c->argv_size += ARGS_STEP;
625                 }
626         }
627         c->argv[c->argc] = NULL;
628 }
629
630 int
631 config_parse_vals(ConfigTable *ct, ConfigArgs *c, int valx)
632 {
633         int     rc = 0;
634
635         snprintf( c->log, sizeof( c->log ), "%s: value #%d",
636                 ct->ad->ad_cname.bv_val, valx );
637         c->argc = 1;
638         c->argv[0] = ct->ad->ad_cname.bv_val;
639
640         if ( ( ct->arg_type & ARG_QUOTE ) && c->line[ 0 ] != '"' ) {
641                 c->argv[c->argc] = c->line;
642                 c->argc++;
643                 c->argv[c->argc] = NULL;
644                 c->tline = NULL;
645         } else {
646                 config_parse_ldif( c );
647         }
648         rc = config_check_vals( ct, c, 1 );
649         ch_free( c->tline );
650         c->tline = NULL;
651
652         if ( rc )
653                 rc = LDAP_CONSTRAINT_VIOLATION;
654
655         return rc;
656 }
657
658 int
659 config_parse_add(ConfigTable *ct, ConfigArgs *c, int valx)
660 {
661         int     rc = 0;
662
663         snprintf( c->log, sizeof( c->log ), "%s: value #%d",
664                 ct->ad->ad_cname.bv_val, valx );
665         c->argc = 1;
666         c->argv[0] = ct->ad->ad_cname.bv_val;
667
668         if ( ( ct->arg_type & ARG_QUOTE ) && c->line[ 0 ] != '"' ) {
669                 c->argv[c->argc] = c->line;
670                 c->argc++;
671                 c->argv[c->argc] = NULL;
672                 c->tline = NULL;
673         } else {
674                 config_parse_ldif( c );
675         }
676         c->op = LDAP_MOD_ADD;
677         rc = config_add_vals( ct, c );
678         ch_free( c->tline );
679
680         return rc;
681 }
682
683 int
684 read_config_file(const char *fname, int depth, ConfigArgs *cf, ConfigTable *cft)
685 {
686         FILE *fp;
687         ConfigTable *ct;
688         ConfigArgs *c;
689         int rc;
690         struct stat s;
691
692         c = ch_calloc( 1, sizeof( ConfigArgs ) );
693         if ( c == NULL ) {
694                 return 1;
695         }
696
697         if ( depth ) {
698                 memcpy( c, cf, sizeof( ConfigArgs ) );
699         } else {
700                 c->depth = depth; /* XXX */
701                 c->bi = NULL;
702                 c->be = NULL;
703         }
704
705         c->valx = -1;
706         c->fname = fname;
707         init_config_argv( c );
708
709         if ( stat( fname, &s ) != 0 ) {
710                 ldap_syslog = 1;
711                 Debug(LDAP_DEBUG_ANY,
712                     "could not stat config file \"%s\": %s (%d)\n",
713                     fname, strerror(errno), errno);
714                 ch_free( c );
715                 return(1);
716         }
717
718         if ( !S_ISREG( s.st_mode ) ) {
719                 ldap_syslog = 1;
720                 Debug(LDAP_DEBUG_ANY,
721                     "regular file expected, got \"%s\"\n",
722                     fname, 0, 0 );
723                 ch_free( c );
724                 return(1);
725         }
726
727         fp = fopen( fname, "r" );
728         if ( fp == NULL ) {
729                 ldap_syslog = 1;
730                 Debug(LDAP_DEBUG_ANY,
731                     "could not open config file \"%s\": %s (%d)\n",
732                     fname, strerror(errno), errno);
733                 ch_free( c );
734                 return(1);
735         }
736
737         Debug(LDAP_DEBUG_CONFIG, "reading config file %s\n", fname, 0, 0);
738
739         fp_getline_init(c);
740
741         c->tline = NULL;
742
743         while ( fp_getline( fp, c ) ) {
744                 /* skip comments and blank lines */
745                 if ( c->line[0] == '#' || c->line[0] == '\0' ) {
746                         continue;
747                 }
748
749                 snprintf( c->log, sizeof( c->log ), "%s: line %d",
750                                 c->fname, c->lineno );
751
752                 c->argc = 0;
753                 ch_free( c->tline );
754                 if ( config_fp_parse_line( c ) ) {
755                         rc = 1;
756                         goto done;
757                 }
758
759                 if ( c->argc < 1 ) {
760                         Debug( LDAP_DEBUG_ANY, "%s: bad config line.\n",
761                                 c->log, 0, 0);
762                         rc = 1;
763                         goto done;
764                 }
765
766                 c->op = SLAP_CONFIG_ADD;
767
768                 ct = config_find_keyword( cft, c );
769                 if ( ct ) {
770                         c->table = Cft_Global;
771                         rc = config_add_vals( ct, c );
772                         if ( !rc ) continue;
773
774                         if ( rc & ARGS_USERLAND ) {
775                                 /* XXX a usertype would be opaque here */
776                                 Debug(LDAP_DEBUG_CONFIG, "%s: unknown user type <%s>\n",
777                                         c->log, c->argv[0], 0);
778                                 rc = 1;
779                                 goto done;
780
781                         } else if ( rc == ARG_BAD_CONF ) {
782                                 rc = 1;
783                                 goto done;
784                         }
785                         
786                 } else if ( c->bi && !c->be ) {
787                         rc = SLAP_CONF_UNKNOWN;
788                         if ( c->bi->bi_cf_ocs ) {
789                                 ct = config_find_keyword( c->bi->bi_cf_ocs->co_table, c );
790                                 if ( ct ) {
791                                         c->table = c->bi->bi_cf_ocs->co_type;
792                                         rc = config_add_vals( ct, c );
793                                 }
794                         }
795                         if ( c->bi->bi_config && rc == SLAP_CONF_UNKNOWN ) {
796                                 rc = (*c->bi->bi_config)(c->bi, c->fname, c->lineno,
797                                         c->argc, c->argv);
798                         }
799                         if ( rc ) {
800                                 switch(rc) {
801                                 case SLAP_CONF_UNKNOWN:
802                                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
803                                                 "<%s> inside backend info definition.\n",
804                                                 c->log, *c->argv, 0);
805                                 default:
806                                         rc = 1;
807                                         goto done;
808                                 }
809                         }
810
811                 } else if ( c->be && c->be != frontendDB ) {
812                         rc = SLAP_CONF_UNKNOWN;
813                         if ( c->be->be_cf_ocs ) {
814                                 ct = config_find_keyword( c->be->be_cf_ocs->co_table, c );
815                                 if ( ct ) {
816                                         c->table = c->be->be_cf_ocs->co_type;
817                                         rc = config_add_vals( ct, c );
818                                 }
819                         }
820                         if ( c->be->be_config && rc == SLAP_CONF_UNKNOWN ) {
821                                 rc = (*c->be->be_config)(c->be, c->fname, c->lineno,
822                                         c->argc, c->argv);
823                         }
824                         if ( rc == SLAP_CONF_UNKNOWN && SLAP_ISGLOBALOVERLAY( frontendDB ) )
825                         {
826                                 /* global overlays may need 
827                                  * definitions inside other databases...
828                                  */
829                                 rc = (*frontendDB->be_config)( frontendDB,
830                                         c->fname, (int)c->lineno, c->argc, c->argv );
831                         }
832
833                         switch ( rc ) {
834                         case 0:
835                                 break;
836
837                         case SLAP_CONF_UNKNOWN:
838                                 Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
839                                         "<%s> inside backend database definition.\n",
840                                         c->log, *c->argv, 0);
841                                 
842                         default:
843                                 rc = 1;
844                                 goto done;
845                         }
846
847                 } else if ( frontendDB->be_config ) {
848                         rc = (*frontendDB->be_config)( frontendDB,
849                                 c->fname, (int)c->lineno, c->argc, c->argv);
850                         if ( rc ) {
851                                 switch(rc) {
852                                 case SLAP_CONF_UNKNOWN:
853                                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
854                                                 "<%s> inside global database definition.\n",
855                                                 c->log, *c->argv, 0);
856
857                                 default:
858                                         rc = 1;
859                                         goto done;
860                                 }
861                         }
862                         
863                 } else {
864                         Debug( LDAP_DEBUG_ANY, "%s: unknown directive "
865                                 "<%s> outside backend info and database definitions.\n",
866                                 c->log, *c->argv, 0);
867                         rc = 1;
868                         goto done;
869                 }
870         }
871
872         rc = 0;
873
874 done:
875         if ( cf ) {
876                 cf->be = c->be;
877                 cf->bi = c->bi;
878         }
879         ch_free(c->tline);
880         fclose(fp);
881         ch_free(c->argv);
882         ch_free(c);
883         return(rc);
884 }
885
886 /* restrictops, allows, disallows, requires, loglevel */
887
888 int
889 bverb_to_mask(struct berval *bword, slap_verbmasks *v) {
890         int i;
891         for(i = 0; !BER_BVISNULL(&v[i].word); i++) {
892                 if(!ber_bvstrcasecmp(bword, &v[i].word)) break;
893         }
894         return(i);
895 }
896
897 int
898 verb_to_mask(const char *word, slap_verbmasks *v) {
899         struct berval   bword;
900         ber_str2bv( word, 0, 0, &bword );
901         return bverb_to_mask( &bword, v );
902 }
903
904 int
905 verbs_to_mask(int argc, char *argv[], slap_verbmasks *v, slap_mask_t *m) {
906         int i, j;
907         for(i = 1; i < argc; i++) {
908                 j = verb_to_mask(argv[i], v);
909                 if(BER_BVISNULL(&v[j].word)) return i;
910                 while (!v[j].mask) j--;
911                 *m |= v[j].mask;
912         }
913         return(0);
914 }
915
916 /* Mask keywords that represent multiple bits should occur before single
917  * bit keywords in the verbmasks array.
918  */
919 int
920 mask_to_verbs(slap_verbmasks *v, slap_mask_t m, BerVarray *bva) {
921         int i, rc = 1;
922
923         if (m) {
924                 for (i=0; !BER_BVISNULL(&v[i].word); i++) {
925                         if (!v[i].mask) continue;
926                         if (( m & v[i].mask ) == v[i].mask ) {
927                                 value_add_one( bva, &v[i].word );
928                                 rc = 0;
929                                 m ^= v[i].mask;
930                                 if ( !m ) break;
931                         }
932                 }
933         }
934         return rc;
935 }
936
937 int
938 slap_verbmasks_init( slap_verbmasks **vp, slap_verbmasks *v )
939 {
940         int             i;
941
942         assert( *vp == NULL );
943
944         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) /* EMPTY */;
945
946         *vp = ch_calloc( i + 1, sizeof( slap_verbmasks ) );
947
948         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) {
949                 ber_dupbv( &(*vp)[ i ].word, &v[ i ].word );
950                 *((slap_mask_t *)&(*vp)[ i ].mask) = v[ i ].mask;
951         }
952
953         BER_BVZERO( &(*vp)[ i ].word );
954
955         return 0;               
956 }
957
958 int
959 slap_verbmasks_destroy( slap_verbmasks *v )
960 {
961         int             i;
962
963         assert( v != NULL );
964
965         for ( i = 0; !BER_BVISNULL( &v[ i ].word ); i++ ) {
966                 ch_free( v[ i ].word.bv_val );
967         }
968
969         ch_free( v );
970
971         return 0;
972 }
973
974 int
975 slap_verbmasks_append(
976         slap_verbmasks  **vp,
977         slap_mask_t     m,
978         struct berval   *v,
979         slap_mask_t     *ignore )
980 {
981         int     i;
982
983         if ( !m ) {
984                 return LDAP_OPERATIONS_ERROR;
985         }
986
987         for ( i = 0; !BER_BVISNULL( &(*vp)[ i ].word ); i++ ) {
988                 if ( !(*vp)[ i ].mask ) continue;
989
990                 if ( ignore != NULL ) {
991                         int     j;
992
993                         for ( j = 0; ignore[ j ] != 0; j++ ) {
994                                 if ( (*vp)[ i ].mask == ignore[ j ] ) {
995                                         goto check_next;
996                                 }
997                         }
998                 }
999
1000                 if ( ( m & (*vp)[ i ].mask ) == (*vp)[ i ].mask ) {
1001                         if ( ber_bvstrcasecmp( v, &(*vp)[ i ].word ) == 0 ) {
1002                                 /* already set; ignore */
1003                                 return LDAP_SUCCESS;
1004                         }
1005                         /* conflicts */
1006                         return LDAP_TYPE_OR_VALUE_EXISTS;
1007                 }
1008
1009                 if ( m & (*vp)[ i ].mask ) {
1010                         /* conflicts */
1011                         return LDAP_CONSTRAINT_VIOLATION;
1012                 }
1013 check_next:;
1014         }
1015
1016         *vp = ch_realloc( *vp, sizeof( slap_verbmasks ) * ( i + 2 ) );
1017         ber_dupbv( &(*vp)[ i ].word, v );
1018         *((slap_mask_t *)&(*vp)[ i ].mask) = m;
1019         BER_BVZERO( &(*vp)[ i + 1 ].word );
1020
1021         return LDAP_SUCCESS;
1022 }
1023
1024 int
1025 enum_to_verb(slap_verbmasks *v, slap_mask_t m, struct berval *bv) {
1026         int i;
1027
1028         for (i=0; !BER_BVISNULL(&v[i].word); i++) {
1029                 if ( m == v[i].mask ) {
1030                         if ( bv != NULL ) {
1031                                 *bv = v[i].word;
1032                         }
1033                         return i;
1034                 }
1035         }
1036         return -1;
1037 }
1038
1039 /* register a new verbmask */
1040 static int
1041 slap_verbmask_register( slap_verbmasks *vm_, slap_verbmasks **vmp, struct berval *bv, int mask )
1042 {
1043         slap_verbmasks  *vm = *vmp;
1044         int             i;
1045
1046         /* check for duplicate word */
1047         /* NOTE: we accept duplicate codes; the first occurrence will be used
1048          * when mapping from mask to verb */
1049         i = verb_to_mask( bv->bv_val, vm );
1050         if ( !BER_BVISNULL( &vm[ i ].word ) ) {
1051                 return -1;
1052         }
1053
1054         for ( i = 0; !BER_BVISNULL( &vm[ i ].word ); i++ )
1055                 ;
1056
1057         if ( vm == vm_ ) {
1058                 /* first time: duplicate array */
1059                 vm = ch_calloc( i + 2, sizeof( slap_verbmasks ) );
1060                 for ( i = 0; !BER_BVISNULL( &vm_[ i ].word ); i++ )
1061                 {
1062                         ber_dupbv( &vm[ i ].word, &vm_[ i ].word );
1063                         *((slap_mask_t*)&vm[ i ].mask) = vm_[ i ].mask;
1064                 }
1065
1066         } else {
1067                 vm = ch_realloc( vm, (i + 2) * sizeof( slap_verbmasks ) );
1068         }
1069
1070         ber_dupbv( &vm[ i ].word, bv );
1071         *((slap_mask_t*)&vm[ i ].mask) = mask;
1072
1073         BER_BVZERO( &vm[ i+1 ].word );
1074
1075         *vmp = vm;
1076
1077         return i;
1078 }
1079
1080 static slap_verbmasks slap_ldap_response_code_[] = {
1081         { BER_BVC("success"),                           LDAP_SUCCESS },
1082
1083         { BER_BVC("operationsError"),                   LDAP_OPERATIONS_ERROR },
1084         { BER_BVC("protocolError"),                     LDAP_PROTOCOL_ERROR },
1085         { BER_BVC("timelimitExceeded"),                 LDAP_TIMELIMIT_EXCEEDED },
1086         { BER_BVC("sizelimitExceeded"),                 LDAP_SIZELIMIT_EXCEEDED },
1087         { BER_BVC("compareFalse"),                      LDAP_COMPARE_FALSE },
1088         { BER_BVC("compareTrue"),                       LDAP_COMPARE_TRUE },
1089
1090         { BER_BVC("authMethodNotSupported"),            LDAP_AUTH_METHOD_NOT_SUPPORTED },
1091         { BER_BVC("strongAuthNotSupported"),            LDAP_STRONG_AUTH_NOT_SUPPORTED },
1092         { BER_BVC("strongAuthRequired"),                LDAP_STRONG_AUTH_REQUIRED },
1093         { BER_BVC("strongerAuthRequired"),              LDAP_STRONGER_AUTH_REQUIRED },
1094 #if 0 /* not LDAPv3 */
1095         { BER_BVC("partialResults"),                    LDAP_PARTIAL_RESULTS },
1096 #endif
1097
1098         { BER_BVC("referral"),                          LDAP_REFERRAL },
1099         { BER_BVC("adminlimitExceeded"),                LDAP_ADMINLIMIT_EXCEEDED },
1100         { BER_BVC("unavailableCriticalExtension"),      LDAP_UNAVAILABLE_CRITICAL_EXTENSION },
1101         { BER_BVC("confidentialityRequired"),           LDAP_CONFIDENTIALITY_REQUIRED },
1102         { BER_BVC("saslBindInProgress"),                LDAP_SASL_BIND_IN_PROGRESS },
1103
1104         { BER_BVC("noSuchAttribute"),                   LDAP_NO_SUCH_ATTRIBUTE },
1105         { BER_BVC("undefinedType"),                     LDAP_UNDEFINED_TYPE },
1106         { BER_BVC("inappropriateMatching"),             LDAP_INAPPROPRIATE_MATCHING },
1107         { BER_BVC("constraintViolation"),               LDAP_CONSTRAINT_VIOLATION },
1108         { BER_BVC("typeOrValueExists"),                 LDAP_TYPE_OR_VALUE_EXISTS },
1109         { BER_BVC("invalidSyntax"),                     LDAP_INVALID_SYNTAX },
1110
1111         { BER_BVC("noSuchObject"),                      LDAP_NO_SUCH_OBJECT },
1112         { BER_BVC("aliasProblem"),                      LDAP_ALIAS_PROBLEM },
1113         { BER_BVC("invalidDnSyntax"),                   LDAP_INVALID_DN_SYNTAX },
1114 #if 0 /* not LDAPv3 */
1115         { BER_BVC("isLeaf"),                            LDAP_IS_LEAF },
1116 #endif
1117         { BER_BVC("aliasDerefProblem"),                 LDAP_ALIAS_DEREF_PROBLEM },
1118
1119         { BER_BVC("proxyAuthzFailure"),                 LDAP_X_PROXY_AUTHZ_FAILURE },
1120         { BER_BVC("inappropriateAuth"),                 LDAP_INAPPROPRIATE_AUTH },
1121         { BER_BVC("invalidCredentials"),                LDAP_INVALID_CREDENTIALS },
1122         { BER_BVC("insufficientAccess"),                LDAP_INSUFFICIENT_ACCESS },
1123
1124         { BER_BVC("busy"),                              LDAP_BUSY },
1125         { BER_BVC("unavailable"),                       LDAP_UNAVAILABLE },
1126         { BER_BVC("unwillingToPerform"),                LDAP_UNWILLING_TO_PERFORM },
1127         { BER_BVC("loopDetect"),                        LDAP_LOOP_DETECT },
1128
1129         { BER_BVC("namingViolation"),                   LDAP_NAMING_VIOLATION },
1130         { BER_BVC("objectClassViolation"),              LDAP_OBJECT_CLASS_VIOLATION },
1131         { BER_BVC("notAllowedOnNonleaf"),               LDAP_NOT_ALLOWED_ON_NONLEAF },
1132         { BER_BVC("notAllowedOnRdn"),                   LDAP_NOT_ALLOWED_ON_RDN },
1133         { BER_BVC("alreadyExists"),                     LDAP_ALREADY_EXISTS },
1134         { BER_BVC("noObjectClassMods"),                 LDAP_NO_OBJECT_CLASS_MODS },
1135         { BER_BVC("resultsTooLarge"),                   LDAP_RESULTS_TOO_LARGE },
1136         { BER_BVC("affectsMultipleDsas"),               LDAP_AFFECTS_MULTIPLE_DSAS },
1137
1138         { BER_BVC("other"),                             LDAP_OTHER },
1139
1140         /* extension-specific */
1141
1142         { BER_BVC("cupResourcesExhausted"),             LDAP_CUP_RESOURCES_EXHAUSTED },
1143         { BER_BVC("cupSecurityViolation"),              LDAP_CUP_SECURITY_VIOLATION },
1144         { BER_BVC("cupInvalidData"),                    LDAP_CUP_INVALID_DATA },
1145         { BER_BVC("cupUnsupportedScheme"),              LDAP_CUP_UNSUPPORTED_SCHEME },
1146         { BER_BVC("cupReloadRequired"),                 LDAP_CUP_RELOAD_REQUIRED },
1147
1148         { BER_BVC("cancelled"),                         LDAP_CANCELLED },
1149         { BER_BVC("noSuchOperation"),                   LDAP_NO_SUCH_OPERATION },
1150         { BER_BVC("tooLate"),                           LDAP_TOO_LATE },
1151         { BER_BVC("cannotCancel"),                      LDAP_CANNOT_CANCEL },
1152
1153         { BER_BVC("assertionFailed"),                   LDAP_ASSERTION_FAILED },
1154
1155         { BER_BVC("proxiedAuthorizationDenied"),        LDAP_PROXIED_AUTHORIZATION_DENIED },
1156
1157         { BER_BVC("syncRefreshRequired"),               LDAP_SYNC_REFRESH_REQUIRED },
1158
1159         { BER_BVC("noOperation"),                       LDAP_X_NO_OPERATION },
1160
1161         { BER_BVNULL,                           0 }
1162 };
1163
1164 slap_verbmasks *slap_ldap_response_code = slap_ldap_response_code_;
1165
1166 int
1167 slap_ldap_response_code_register( struct berval *bv, int err )
1168 {
1169         return slap_verbmask_register( slap_ldap_response_code_,
1170                 &slap_ldap_response_code, bv, err );
1171 }
1172
1173 #ifdef HAVE_TLS
1174 static slap_verbmasks tlskey[] = {
1175         { BER_BVC("no"),        SB_TLS_OFF },
1176         { BER_BVC("yes"),       SB_TLS_ON },
1177         { BER_BVC("critical"),  SB_TLS_CRITICAL },
1178         { BER_BVNULL, 0 }
1179 };
1180
1181 static slap_verbmasks crlkeys[] = {
1182                 { BER_BVC("none"),      LDAP_OPT_X_TLS_CRL_NONE },
1183                 { BER_BVC("peer"),      LDAP_OPT_X_TLS_CRL_PEER },
1184                 { BER_BVC("all"),       LDAP_OPT_X_TLS_CRL_ALL },
1185                 { BER_BVNULL, 0 }
1186         };
1187
1188 static slap_verbmasks vfykeys[] = {
1189                 { BER_BVC("never"),     LDAP_OPT_X_TLS_NEVER },
1190                 { BER_BVC("demand"),    LDAP_OPT_X_TLS_DEMAND },
1191                 { BER_BVC("try"),       LDAP_OPT_X_TLS_TRY },
1192                 { BER_BVC("hard"),      LDAP_OPT_X_TLS_HARD },
1193                 { BER_BVNULL, 0 }
1194         };
1195 #endif
1196
1197 static slap_verbmasks methkey[] = {
1198         { BER_BVC("none"),      LDAP_AUTH_NONE },
1199         { BER_BVC("simple"),    LDAP_AUTH_SIMPLE },
1200 #ifdef HAVE_CYRUS_SASL
1201         { BER_BVC("sasl"),      LDAP_AUTH_SASL },
1202 #endif
1203         { BER_BVNULL, 0 }
1204 };
1205
1206 static slap_verbmasks versionkey[] = {
1207         { BER_BVC("2"),         LDAP_VERSION2 },
1208         { BER_BVC("3"),         LDAP_VERSION3 },
1209         { BER_BVNULL, 0 }
1210 };
1211
1212 static slap_cf_aux_table bindkey[] = {
1213         { BER_BVC("uri="), offsetof(slap_bindconf, sb_uri), 'b', 1, NULL },
1214         { BER_BVC("version="), offsetof(slap_bindconf, sb_version), 'i', 0, versionkey },
1215         { BER_BVC("bindmethod="), offsetof(slap_bindconf, sb_method), 'i', 0, methkey },
1216         { BER_BVC("timeout="), offsetof(slap_bindconf, sb_timeout_api), 'i', 0, NULL },
1217         { BER_BVC("network-timeout="), offsetof(slap_bindconf, sb_timeout_net), 'i', 0, NULL },
1218         { BER_BVC("binddn="), offsetof(slap_bindconf, sb_binddn), 'b', 1, (slap_verbmasks *)dnNormalize },
1219         { BER_BVC("credentials="), offsetof(slap_bindconf, sb_cred), 'b', 1, NULL },
1220         { BER_BVC("saslmech="), offsetof(slap_bindconf, sb_saslmech), 'b', 0, NULL },
1221         { BER_BVC("secprops="), offsetof(slap_bindconf, sb_secprops), 's', 0, NULL },
1222         { BER_BVC("realm="), offsetof(slap_bindconf, sb_realm), 'b', 0, NULL },
1223         { BER_BVC("authcID="), offsetof(slap_bindconf, sb_authcId), 'b', 1, NULL },
1224         { BER_BVC("authzID="), offsetof(slap_bindconf, sb_authzId), 'b', 1, (slap_verbmasks *)authzNormalize },
1225 #ifdef HAVE_TLS
1226         { BER_BVC("starttls="), offsetof(slap_bindconf, sb_tls), 'i', 0, tlskey },
1227
1228         /* NOTE: replace "13" with the actual index
1229          * of the first TLS-related line */
1230 #define aux_TLS (bindkey+13)    /* beginning of TLS keywords */
1231
1232         { BER_BVC("tls_cert="), offsetof(slap_bindconf, sb_tls_cert), 's', 1, NULL },
1233         { BER_BVC("tls_key="), offsetof(slap_bindconf, sb_tls_key), 's', 1, NULL },
1234         { BER_BVC("tls_cacert="), offsetof(slap_bindconf, sb_tls_cacert), 's', 1, NULL },
1235         { BER_BVC("tls_cacertdir="), offsetof(slap_bindconf, sb_tls_cacertdir), 's', 1, NULL },
1236         { BER_BVC("tls_reqcert="), offsetof(slap_bindconf, sb_tls_reqcert), 's', 1, NULL },
1237         { BER_BVC("tls_cipher_suite="), offsetof(slap_bindconf, sb_tls_cipher_suite), 's', 1, NULL },
1238         { BER_BVC("tls_protocol_min="), offsetof(slap_bindconf, sb_tls_protocol_min), 's', 1, NULL },
1239 #ifdef HAVE_OPENSSL_CRL
1240         { BER_BVC("tls_crlcheck="), offsetof(slap_bindconf, sb_tls_crlcheck), 's', 1, NULL },
1241 #endif
1242 #endif
1243         { BER_BVNULL, 0, 0, 0, NULL }
1244 };
1245
1246 /*
1247  * 's': char *
1248  * 'b': struct berval; if !NULL, normalize using ((slap_mr_normalize_func *)aux)
1249  * 'i': int; if !NULL, compute using ((slap_verbmasks *)aux)
1250  * 'u': unsigned
1251  * 'I': long
1252  * 'U': unsigned long
1253  */
1254
1255 int
1256 slap_cf_aux_table_parse( const char *word, void *dst, slap_cf_aux_table *tab0, LDAP_CONST char *tabmsg )
1257 {
1258         int rc = SLAP_CONF_UNKNOWN;
1259         slap_cf_aux_table *tab;
1260
1261         for ( tab = tab0; !BER_BVISNULL( &tab->key ); tab++ ) {
1262                 if ( !strncasecmp( word, tab->key.bv_val, tab->key.bv_len ) ) {
1263                         char **cptr;
1264                         int *iptr, j;
1265                         unsigned *uptr;
1266                         long *lptr;
1267                         unsigned long *ulptr;
1268                         struct berval *bptr;
1269                         const char *val = word + tab->key.bv_len;
1270
1271                         switch ( tab->type ) {
1272                         case 's':
1273                                 cptr = (char **)((char *)dst + tab->off);
1274                                 *cptr = ch_strdup( val );
1275                                 rc = 0;
1276                                 break;
1277
1278                         case 'b':
1279                                 bptr = (struct berval *)((char *)dst + tab->off);
1280                                 if ( tab->aux != NULL ) {
1281                                         struct berval   dn;
1282                                         slap_mr_normalize_func *normalize = (slap_mr_normalize_func *)tab->aux;
1283
1284                                         ber_str2bv( val, 0, 0, &dn );
1285                                         rc = normalize( 0, NULL, NULL, &dn, bptr, NULL );
1286
1287                                 } else {
1288                                         ber_str2bv( val, 0, 1, bptr );
1289                                         rc = 0;
1290                                 }
1291                                 break;
1292
1293                         case 'i':
1294                                 iptr = (int *)((char *)dst + tab->off);
1295
1296                                 if ( tab->aux != NULL ) {
1297                                         slap_verbmasks *aux = (slap_verbmasks *)tab->aux;
1298
1299                                         assert( aux != NULL );
1300
1301                                         rc = 1;
1302                                         for ( j = 0; !BER_BVISNULL( &aux[j].word ); j++ ) {
1303                                                 if ( !strcasecmp( val, aux[j].word.bv_val ) ) {
1304                                                         *iptr = aux[j].mask;
1305                                                         rc = 0;
1306                                                         break;
1307                                                 }
1308                                         }
1309
1310                                 } else {
1311                                         rc = lutil_atoix( iptr, val, 0 );
1312                                 }
1313                                 break;
1314
1315                         case 'u':
1316                                 uptr = (unsigned *)((char *)dst + tab->off);
1317
1318                                 rc = lutil_atoux( uptr, val, 0 );
1319                                 break;
1320
1321                         case 'I':
1322                                 lptr = (long *)((char *)dst + tab->off);
1323
1324                                 rc = lutil_atolx( lptr, val, 0 );
1325                                 break;
1326
1327                         case 'U':
1328                                 ulptr = (unsigned long *)((char *)dst + tab->off);
1329
1330                                 rc = lutil_atoulx( ulptr, val, 0 );
1331                                 break;
1332                         }
1333
1334                         if ( rc ) {
1335                                 Debug( LDAP_DEBUG_ANY, "invalid %s value %s\n",
1336                                         tabmsg, word, 0 );
1337                         }
1338                         
1339                         return rc;
1340                 }
1341         }
1342
1343         return rc;
1344 }
1345
1346 int
1347 slap_cf_aux_table_unparse( void *src, struct berval *bv, slap_cf_aux_table *tab0 )
1348 {
1349         char buf[AC_LINE_MAX], *ptr;
1350         slap_cf_aux_table *tab;
1351         struct berval tmp;
1352
1353         ptr = buf;
1354         for (tab = tab0; !BER_BVISNULL(&tab->key); tab++ ) {
1355                 char **cptr;
1356                 int *iptr, i;
1357                 unsigned *uptr;
1358                 long *lptr;
1359                 unsigned long *ulptr;
1360                 struct berval *bptr;
1361
1362                 cptr = (char **)((char *)src + tab->off);
1363
1364                 switch ( tab->type ) {
1365                 case 'b':
1366                         bptr = (struct berval *)((char *)src + tab->off);
1367                         cptr = &bptr->bv_val;
1368
1369                 case 's':
1370                         if ( *cptr ) {
1371                                 *ptr++ = ' ';
1372                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1373                                 if ( tab->quote ) *ptr++ = '"';
1374                                 ptr = lutil_strcopy( ptr, *cptr );
1375                                 if ( tab->quote ) *ptr++ = '"';
1376                         }
1377                         break;
1378
1379                 case 'i':
1380                         iptr = (int *)((char *)src + tab->off);
1381
1382                         if ( tab->aux != NULL ) {
1383                                 slap_verbmasks *aux = (slap_verbmasks *)tab->aux;
1384
1385                                 for ( i = 0; !BER_BVISNULL( &aux[i].word ); i++ ) {
1386                                         if ( *iptr == aux[i].mask ) {
1387                                                 *ptr++ = ' ';
1388                                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1389                                                 ptr = lutil_strcopy( ptr, aux[i].word.bv_val );
1390                                                 break;
1391                                         }
1392                                 }
1393
1394                         } else {
1395                                 *ptr++ = ' ';
1396                                 ptr = lutil_strcopy( ptr, tab->key.bv_val );
1397                                 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%d", *iptr );
1398                         }
1399                         break;
1400
1401                 case 'u':
1402                         uptr = (unsigned *)((char *)src + tab->off);
1403                         *ptr++ = ' ';
1404                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1405                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%u", *uptr );
1406                         break;
1407
1408                 case 'I':
1409                         lptr = (long *)((char *)src + tab->off);
1410                         *ptr++ = ' ';
1411                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1412                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%ld", *lptr );
1413                         break;
1414
1415                 case 'U':
1416                         ulptr = (unsigned long *)((char *)src + tab->off);
1417                         *ptr++ = ' ';
1418                         ptr = lutil_strcopy( ptr, tab->key.bv_val );
1419                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ), "%lu", *ulptr );
1420                         break;
1421
1422                 default:
1423                         assert( 0 );
1424                 }
1425         }
1426         tmp.bv_val = buf;
1427         tmp.bv_len = ptr - buf;
1428         ber_dupbv( bv, &tmp );
1429         return 0;
1430 }
1431
1432 int
1433 slap_tls_get_config( LDAP *ld, int opt, char **val )
1434 {
1435 #ifdef HAVE_TLS
1436         slap_verbmasks *keys;
1437         int i, ival;
1438
1439         *val = NULL;
1440         switch( opt ) {
1441         case LDAP_OPT_X_TLS_CRLCHECK:
1442                 keys = crlkeys;
1443                 break;
1444         case LDAP_OPT_X_TLS_REQUIRE_CERT:
1445                 keys = vfykeys;
1446                 break;
1447         case LDAP_OPT_X_TLS_PROTOCOL_MIN: {
1448                 char buf[8];
1449                 ldap_pvt_tls_get_option( ld, opt, &ival );
1450                 snprintf( buf, sizeof( buf ), "%d.%d",
1451                         ( ival >> 8 ) & 0xff, ival & 0xff );
1452                 *val = ch_strdup( buf );
1453                 return 0;
1454                 }
1455         default:
1456                 return -1;
1457         }
1458         ldap_pvt_tls_get_option( ld, opt, &ival );
1459         for (i=0; !BER_BVISNULL(&keys[i].word); i++) {
1460                 if (keys[i].mask == ival) {
1461                         *val = ch_strdup( keys[i].word.bv_val );
1462                         return 0;
1463                 }
1464         }
1465 #endif
1466         return -1;
1467 }
1468
1469 int
1470 bindconf_tls_parse( const char *word, slap_bindconf *bc )
1471 {
1472 #ifdef HAVE_TLS
1473         if ( slap_cf_aux_table_parse( word, bc, aux_TLS, "tls config" ) == 0 ) {
1474                 bc->sb_tls_do_init = 1;
1475                 return 0;
1476         }
1477 #endif
1478         return -1;
1479 }
1480
1481 int
1482 bindconf_tls_unparse( slap_bindconf *bc, struct berval *bv )
1483 {
1484 #ifdef HAVE_TLS
1485         return slap_cf_aux_table_unparse( bc, bv, aux_TLS );
1486 #endif
1487         return -1;
1488 }
1489
1490 int
1491 bindconf_parse( const char *word, slap_bindconf *bc )
1492 {
1493 #ifdef HAVE_TLS
1494         /* Detect TLS config changes explicitly */
1495         if ( bindconf_tls_parse( word, bc ) == 0 ) {
1496                 return 0;
1497         }
1498 #endif
1499         return slap_cf_aux_table_parse( word, bc, bindkey, "bind config" );
1500 }
1501
1502 int
1503 bindconf_unparse( slap_bindconf *bc, struct berval *bv )
1504 {
1505         return slap_cf_aux_table_unparse( bc, bv, bindkey );
1506 }
1507
1508 void bindconf_free( slap_bindconf *bc ) {
1509         if ( !BER_BVISNULL( &bc->sb_uri ) ) {
1510                 ch_free( bc->sb_uri.bv_val );
1511                 BER_BVZERO( &bc->sb_uri );
1512         }
1513         if ( !BER_BVISNULL( &bc->sb_binddn ) ) {
1514                 ch_free( bc->sb_binddn.bv_val );
1515                 BER_BVZERO( &bc->sb_binddn );
1516         }
1517         if ( !BER_BVISNULL( &bc->sb_cred ) ) {
1518                 ch_free( bc->sb_cred.bv_val );
1519                 BER_BVZERO( &bc->sb_cred );
1520         }
1521         if ( !BER_BVISNULL( &bc->sb_saslmech ) ) {
1522                 ch_free( bc->sb_saslmech.bv_val );
1523                 BER_BVZERO( &bc->sb_saslmech );
1524         }
1525         if ( bc->sb_secprops ) {
1526                 ch_free( bc->sb_secprops );
1527                 bc->sb_secprops = NULL;
1528         }
1529         if ( !BER_BVISNULL( &bc->sb_realm ) ) {
1530                 ch_free( bc->sb_realm.bv_val );
1531                 BER_BVZERO( &bc->sb_realm );
1532         }
1533         if ( !BER_BVISNULL( &bc->sb_authcId ) ) {
1534                 ch_free( bc->sb_authcId.bv_val );
1535                 BER_BVZERO( &bc->sb_authcId );
1536         }
1537         if ( !BER_BVISNULL( &bc->sb_authzId ) ) {
1538                 ch_free( bc->sb_authzId.bv_val );
1539                 BER_BVZERO( &bc->sb_authzId );
1540         }
1541 #ifdef HAVE_TLS
1542         if ( bc->sb_tls_cert ) {
1543                 ch_free( bc->sb_tls_cert );
1544                 bc->sb_tls_cert = NULL;
1545         }
1546         if ( bc->sb_tls_key ) {
1547                 ch_free( bc->sb_tls_key );
1548                 bc->sb_tls_key = NULL;
1549         }
1550         if ( bc->sb_tls_cacert ) {
1551                 ch_free( bc->sb_tls_cacert );
1552                 bc->sb_tls_cacert = NULL;
1553         }
1554         if ( bc->sb_tls_cacertdir ) {
1555                 ch_free( bc->sb_tls_cacertdir );
1556                 bc->sb_tls_cacertdir = NULL;
1557         }
1558         if ( bc->sb_tls_reqcert ) {
1559                 ch_free( bc->sb_tls_reqcert );
1560                 bc->sb_tls_reqcert = NULL;
1561         }
1562         if ( bc->sb_tls_cipher_suite ) {
1563                 ch_free( bc->sb_tls_cipher_suite );
1564                 bc->sb_tls_cipher_suite = NULL;
1565         }
1566         if ( bc->sb_tls_protocol_min ) {
1567                 ch_free( bc->sb_tls_protocol_min );
1568                 bc->sb_tls_protocol_min = NULL;
1569         }
1570 #ifdef HAVE_OPENSSL_CRL
1571         if ( bc->sb_tls_crlcheck ) {
1572                 ch_free( bc->sb_tls_crlcheck );
1573                 bc->sb_tls_crlcheck = NULL;
1574         }
1575 #endif
1576 #endif
1577 }
1578
1579 void
1580 bindconf_tls_defaults( slap_bindconf *bc )
1581 {
1582 #ifdef HAVE_TLS
1583         if ( bc->sb_tls_do_init ) {
1584                 if ( !bc->sb_tls_cacert )
1585                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CACERTFILE,
1586                                 &bc->sb_tls_cacert );
1587                 if ( !bc->sb_tls_cacertdir )
1588                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CACERTDIR,
1589                                 &bc->sb_tls_cacertdir );
1590                 if ( !bc->sb_tls_cert )
1591                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CERTFILE,
1592                                 &bc->sb_tls_cert );
1593                 if ( !bc->sb_tls_key )
1594                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_KEYFILE,
1595                                 &bc->sb_tls_key );
1596                 if ( !bc->sb_tls_cipher_suite )
1597                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CIPHER_SUITE,
1598                                 &bc->sb_tls_cipher_suite );
1599                 if ( !bc->sb_tls_reqcert )
1600                         bc->sb_tls_reqcert = ch_strdup("demand");
1601 #ifdef HAVE_OPENSSL_CRL
1602                 if ( !bc->sb_tls_crlcheck )
1603                         slap_tls_get_config( slap_tls_ld, LDAP_OPT_X_TLS_CRLCHECK,
1604                                 &bc->sb_tls_crlcheck );
1605 #endif
1606         }
1607 #endif
1608 }
1609
1610 #ifdef HAVE_TLS
1611 static struct {
1612         const char *key;
1613         size_t offset;
1614         int opt;
1615 } bindtlsopts[] = {
1616         { "tls_cert", offsetof(slap_bindconf, sb_tls_cert), LDAP_OPT_X_TLS_CERTFILE },
1617         { "tls_key", offsetof(slap_bindconf, sb_tls_key), LDAP_OPT_X_TLS_KEYFILE },
1618         { "tls_cacert", offsetof(slap_bindconf, sb_tls_cacert), LDAP_OPT_X_TLS_CACERTFILE },
1619         { "tls_cacertdir", offsetof(slap_bindconf, sb_tls_cacertdir), LDAP_OPT_X_TLS_CACERTDIR },
1620         { "tls_cipher_suite", offsetof(slap_bindconf, sb_tls_cipher_suite), LDAP_OPT_X_TLS_CIPHER_SUITE },
1621         { "tls_protocol_min", offsetof(slap_bindconf, sb_tls_protocol_min), LDAP_OPT_X_TLS_PROTOCOL_MIN },
1622         {0, 0}
1623 };
1624
1625 int bindconf_tls_set( slap_bindconf *bc, LDAP *ld )
1626 {
1627         int i, rc, newctx = 0, res = 0;
1628         char *ptr = (char *)bc, **word;
1629
1630         bc->sb_tls_do_init = 0;
1631
1632         for (i=0; bindtlsopts[i].opt; i++) {
1633                 word = (char **)(ptr + bindtlsopts[i].offset);
1634                 if ( *word ) {
1635                         rc = ldap_set_option( ld, bindtlsopts[i].opt, *word );
1636                         if ( rc ) {
1637                                 Debug( LDAP_DEBUG_ANY,
1638                                         "bindconf_tls_set: failed to set %s to %s\n",
1639                                                 bindtlsopts[i].key, *word, 0 );
1640                                 res = -1;
1641                         } else
1642                                 newctx = 1;
1643                 }
1644         }
1645         if ( bc->sb_tls_reqcert ) {
1646                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_REQUIRE_CERT,
1647                         bc->sb_tls_reqcert );
1648                 if ( rc ) {
1649                         Debug( LDAP_DEBUG_ANY,
1650                                 "bindconf_tls_set: failed to set tls_reqcert to %s\n",
1651                                         bc->sb_tls_reqcert, 0, 0 );
1652                         res = -1;
1653                 } else
1654                         newctx = 1;
1655         }
1656         if ( bc->sb_tls_protocol_min ) {
1657                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_PROTOCOL_MIN,
1658                         bc->sb_tls_protocol_min );
1659                 if ( rc ) {
1660                         Debug( LDAP_DEBUG_ANY,
1661                                 "bindconf_tls_set: failed to set tls_protocol_min to %s\n",
1662                                         bc->sb_tls_protocol_min, 0, 0 );
1663                         res = -1;
1664                 } else
1665                         newctx = 1;
1666         }
1667 #ifdef HAVE_OPENSSL_CRL
1668         if ( bc->sb_tls_crlcheck ) {
1669                 rc = ldap_pvt_tls_config( ld, LDAP_OPT_X_TLS_CRLCHECK,
1670                         bc->sb_tls_crlcheck );
1671                 if ( rc ) {
1672                         Debug( LDAP_DEBUG_ANY,
1673                                 "bindconf_tls_set: failed to set tls_crlcheck to %s\n",
1674                                         bc->sb_tls_crlcheck, 0, 0 );
1675                         res = -1;
1676                 } else
1677                         newctx = 1;
1678         }
1679 #endif
1680         if ( newctx ) {
1681                 int opt = 0;
1682
1683                 if ( bc->sb_tls_ctx ) {
1684                         ldap_pvt_tls_ctx_free( bc->sb_tls_ctx );
1685                         bc->sb_tls_ctx = NULL;
1686                 }
1687                 rc = ldap_set_option( ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
1688                 if ( rc )
1689                         res = rc;
1690                 else
1691                         ldap_get_option( ld, LDAP_OPT_X_TLS_CTX, &bc->sb_tls_ctx );
1692         }
1693         
1694         return res;
1695 }
1696 #endif
1697
1698 /*
1699  * connect to a client using the bindconf data
1700  * note: should move "version" into bindconf...
1701  */
1702 int
1703 slap_client_connect( LDAP **ldp, slap_bindconf *sb )
1704 {
1705         LDAP            *ld = NULL;
1706         int             rc;
1707         struct timeval tv;
1708
1709         /* Init connection to master */
1710         rc = ldap_initialize( &ld, sb->sb_uri.bv_val );
1711         if ( rc != LDAP_SUCCESS ) {
1712                 Debug( LDAP_DEBUG_ANY,
1713                         "slap_client_connect: "
1714                         "ldap_initialize(%s) failed (%d)\n",
1715                         sb->sb_uri.bv_val, rc, 0 );
1716                 return rc;
1717         }
1718
1719         if ( sb->sb_version != 0 ) {
1720                 ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
1721                         (const void *)&sb->sb_version );
1722         }
1723
1724         if ( sb->sb_timeout_api ) {
1725                 tv.tv_sec = sb->sb_timeout_api;
1726                 tv.tv_usec = 0;
1727                 ldap_set_option( ld, LDAP_OPT_TIMEOUT, &tv );
1728         }
1729
1730         if ( sb->sb_timeout_net ) {
1731                 tv.tv_sec = sb->sb_timeout_net;
1732                 tv.tv_usec = 0;
1733                 ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, &tv );
1734         }
1735
1736 #ifdef HAVE_TLS
1737         if ( sb->sb_tls_do_init ) {
1738                 rc = bindconf_tls_set( sb, ld );
1739
1740         } else if ( sb->sb_tls_ctx ) {
1741                 rc = ldap_set_option( ld, LDAP_OPT_X_TLS_CTX,
1742                         sb->sb_tls_ctx );
1743         }
1744
1745         if ( rc ) {
1746                 Debug( LDAP_DEBUG_ANY,
1747                         "slap_client_connect: "
1748                         "URI=%s TLS context initialization failed (%d)\n",
1749                         sb->sb_uri.bv_val, rc, 0 );
1750                 return rc;
1751         }
1752 #endif
1753
1754         /* Bind */
1755         if ( sb->sb_tls ) {
1756                 rc = ldap_start_tls_s( ld, NULL, NULL );
1757                 if ( rc != LDAP_SUCCESS ) {
1758                         Debug( LDAP_DEBUG_ANY,
1759                                 "slap_client_connect: URI=%s "
1760                                 "%s, ldap_start_tls failed (%d)\n",
1761                                 sb->sb_uri.bv_val,
1762                                 sb->sb_tls == SB_TLS_CRITICAL ?
1763                                         "Error" : "Warning",
1764                                 rc );
1765                         if ( sb->sb_tls == SB_TLS_CRITICAL ) {
1766                                 goto done;
1767                         }
1768                 }
1769         }
1770
1771         if ( sb->sb_method == LDAP_AUTH_SASL ) {
1772 #ifdef HAVE_CYRUS_SASL
1773                 void *defaults;
1774
1775                 if ( sb->sb_secprops != NULL ) {
1776                         rc = ldap_set_option( ld,
1777                                 LDAP_OPT_X_SASL_SECPROPS, sb->sb_secprops);
1778
1779                         if( rc != LDAP_OPT_SUCCESS ) {
1780                                 Debug( LDAP_DEBUG_ANY,
1781                                         "slap_client_connect: "
1782                                         "error, ldap_set_option "
1783                                         "(%s,SECPROPS,\"%s\") failed!\n",
1784                                         sb->sb_uri.bv_val, sb->sb_secprops, 0 );
1785                                 goto done;
1786                         }
1787                 }
1788
1789                 defaults = lutil_sasl_defaults( ld,
1790                         sb->sb_saslmech.bv_val,
1791                         sb->sb_realm.bv_val,
1792                         sb->sb_authcId.bv_val,
1793                         sb->sb_cred.bv_val,
1794                         sb->sb_authzId.bv_val );
1795                 if ( defaults == NULL ) {
1796                         rc = LDAP_OTHER;
1797                         goto done;
1798                 }
1799
1800                 rc = ldap_sasl_interactive_bind_s( ld,
1801                                 sb->sb_binddn.bv_val,
1802                                 sb->sb_saslmech.bv_val,
1803                                 NULL, NULL,
1804                                 LDAP_SASL_QUIET,
1805                                 lutil_sasl_interact,
1806                                 defaults );
1807
1808                 lutil_sasl_freedefs( defaults );
1809
1810                 /* FIXME: different error behaviors according to
1811                  *      1) return code
1812                  *      2) on err policy : exit, retry, backoff ...
1813                  */
1814                 if ( rc != LDAP_SUCCESS ) {
1815                         static struct berval bv_GSSAPI = BER_BVC( "GSSAPI" );
1816
1817                         Debug( LDAP_DEBUG_ANY, "slap_client_connect: URI=%s "
1818                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
1819                                 sb->sb_uri.bv_val, rc, 0 );
1820
1821                         /* FIXME (see above comment) */
1822                         /* if Kerberos credentials cache is not active, retry */
1823                         if ( ber_bvcmp( &sb->sb_saslmech, &bv_GSSAPI ) == 0 &&
1824                                 rc == LDAP_LOCAL_ERROR )
1825                         {
1826                                 rc = LDAP_SERVER_DOWN;
1827                         }
1828
1829                         goto done;
1830                 }
1831 #else /* HAVE_CYRUS_SASL */
1832                 /* Should never get here, we trapped this at config time */
1833                 assert(0);
1834                 Debug( LDAP_DEBUG_SYNC, "not compiled with SASL support\n", 0, 0, 0 );
1835                 rc = LDAP_OTHER;
1836                 goto done;
1837 #endif
1838
1839         } else if ( sb->sb_method == LDAP_AUTH_SIMPLE ) {
1840                 rc = ldap_sasl_bind_s( ld,
1841                         sb->sb_binddn.bv_val, LDAP_SASL_SIMPLE,
1842                         &sb->sb_cred, NULL, NULL, NULL );
1843                 if ( rc != LDAP_SUCCESS ) {
1844                         Debug( LDAP_DEBUG_ANY, "slap_client_connect: "
1845                                 "URI=%s DN=\"%s\" "
1846                                 "ldap_sasl_bind_s failed (%d)\n",
1847                                 sb->sb_uri.bv_val, sb->sb_binddn.bv_val, rc );
1848                         goto done;
1849                 }
1850         }
1851
1852 done:;
1853         if ( rc ) {
1854                 if ( ld ) {
1855                         ldap_unbind_ext( ld, NULL, NULL );
1856                         *ldp = NULL;
1857                 }
1858
1859         } else {
1860                 *ldp = ld;
1861         }
1862
1863         return rc;
1864 }
1865
1866 /* -------------------------------------- */
1867
1868
1869 static char *
1870 strtok_quote( char *line, char *sep, char **quote_ptr )
1871 {
1872         int             inquote;
1873         char            *tmp;
1874         static char     *next;
1875
1876         *quote_ptr = NULL;
1877         if ( line != NULL ) {
1878                 next = line;
1879         }
1880         while ( *next && strchr( sep, *next ) ) {
1881                 next++;
1882         }
1883
1884         if ( *next == '\0' ) {
1885                 next = NULL;
1886                 return( NULL );
1887         }
1888         tmp = next;
1889
1890         for ( inquote = 0; *next; ) {
1891                 switch ( *next ) {
1892                 case '"':
1893                         if ( inquote ) {
1894                                 inquote = 0;
1895                         } else {
1896                                 inquote = 1;
1897                         }
1898                         AC_MEMCPY( next, next + 1, strlen( next + 1 ) + 1 );
1899                         break;
1900
1901                 case '\\':
1902                         if ( next[1] )
1903                                 AC_MEMCPY( next,
1904                                             next + 1, strlen( next + 1 ) + 1 );
1905                         next++;         /* dont parse the escaped character */
1906                         break;
1907
1908                 default:
1909                         if ( ! inquote ) {
1910                                 if ( strchr( sep, *next ) != NULL ) {
1911                                         *quote_ptr = next;
1912                                         *next++ = '\0';
1913                                         return( tmp );
1914                                 }
1915                         }
1916                         next++;
1917                         break;
1918                 }
1919         }
1920
1921         return( tmp );
1922 }
1923
1924 static char     buf[AC_LINE_MAX];
1925 static char     *line;
1926 static size_t lmax, lcur;
1927
1928 #define CATLINE( buf ) \
1929         do { \
1930                 size_t len = strlen( buf ); \
1931                 while ( lcur + len + 1 > lmax ) { \
1932                         lmax += AC_LINE_MAX; \
1933                         line = (char *) ch_realloc( line, lmax ); \
1934                 } \
1935                 strcpy( line + lcur, buf ); \
1936                 lcur += len; \
1937         } while( 0 )
1938
1939 static void
1940 fp_getline_init(ConfigArgs *c) {
1941         c->lineno = -1;
1942         buf[0] = '\0';
1943 }
1944
1945 static int
1946 fp_getline( FILE *fp, ConfigArgs *c )
1947 {
1948         char    *p;
1949
1950         lcur = 0;
1951         CATLINE(buf);
1952         c->lineno++;
1953
1954         /* avoid stack of bufs */
1955         if ( strncasecmp( line, "include", STRLENOF( "include" ) ) == 0 ) {
1956                 buf[0] = '\0';
1957                 c->line = line;
1958                 return(1);
1959         }
1960
1961         while ( fgets( buf, sizeof( buf ), fp ) ) {
1962                 p = strchr( buf, '\n' );
1963                 if ( p ) {
1964                         if ( p > buf && p[-1] == '\r' ) {
1965                                 --p;
1966                         }
1967                         *p = '\0';
1968                 }
1969                 /* XXX ugly */
1970                 c->line = line;
1971                 if ( line[0]
1972                                 && ( p = line + strlen( line ) - 1 )[0] == '\\'
1973                                 && p[-1] != '\\' )
1974                 {
1975                         p[0] = '\0';
1976                         lcur--;
1977                         
1978                 } else {
1979                         if ( !isspace( (unsigned char)buf[0] ) ) {
1980                                 return(1);
1981                         }
1982                         buf[0] = ' ';
1983                 }
1984                 CATLINE(buf);
1985                 c->lineno++;
1986         }
1987
1988         buf[0] = '\0';
1989         c->line = line;
1990         return(line[0] ? 1 : 0);
1991 }
1992
1993 int
1994 config_fp_parse_line(ConfigArgs *c)
1995 {
1996         char *token;
1997         static char *const hide[] = {
1998                 "rootpw", "replica", "syncrepl",  /* in slapd */
1999                 "acl-bind", "acl-method", "idassert-bind",  /* in back-ldap */
2000                 "acl-passwd", "bindpw",  /* in back-<ldap/meta> */
2001                 "pseudorootpw",  /* in back-meta */
2002                 "dbpasswd",  /* in back-sql */
2003                 NULL
2004         };
2005         char *quote_ptr;
2006         int i = (int)(sizeof(hide)/sizeof(hide[0])) - 1;
2007
2008         c->tline = ch_strdup(c->line);
2009         token = strtok_quote(c->tline, " \t", &quote_ptr);
2010
2011         if(token) for(i = 0; hide[i]; i++) if(!strcasecmp(token, hide[i])) break;
2012         if(quote_ptr) *quote_ptr = ' ';
2013         Debug(LDAP_DEBUG_CONFIG, "line %d (%s%s)\n", c->lineno,
2014                 hide[i] ? hide[i] : c->line, hide[i] ? " ***" : "");
2015         if(quote_ptr) *quote_ptr = '\0';
2016
2017         for(;; token = strtok_quote(NULL, " \t", &quote_ptr)) {
2018                 if(c->argc >= c->argv_size) {
2019                         char **tmp;
2020                         tmp = ch_realloc(c->argv, (c->argv_size + ARGS_STEP) * sizeof(*c->argv));
2021                         if(!tmp) {
2022                                 Debug(LDAP_DEBUG_ANY, "line %d: out of memory\n", c->lineno, 0, 0);
2023                                 return -1;
2024                         }
2025                         c->argv = tmp;
2026                         c->argv_size += ARGS_STEP;
2027                 }
2028                 if(token == NULL)
2029                         break;
2030                 c->argv[c->argc++] = token;
2031         }
2032         c->argv[c->argc] = NULL;
2033         return(0);
2034 }
2035
2036 void
2037 config_destroy( )
2038 {
2039         ucdata_unload( UCDATA_ALL );
2040         if ( frontendDB ) {
2041                 /* NOTE: in case of early exit, frontendDB can be NULL */
2042                 if ( frontendDB->be_schemandn.bv_val )
2043                         free( frontendDB->be_schemandn.bv_val );
2044                 if ( frontendDB->be_schemadn.bv_val )
2045                         free( frontendDB->be_schemadn.bv_val );
2046                 if ( frontendDB->be_acl )
2047                         acl_destroy( frontendDB->be_acl );
2048         }
2049         free( line );
2050         if ( slapd_args_file )
2051                 free ( slapd_args_file );
2052         if ( slapd_pid_file )
2053                 free ( slapd_pid_file );
2054         if ( default_passwd_hash )
2055                 ldap_charray_free( default_passwd_hash );
2056 }
2057
2058 char **
2059 slap_str2clist( char ***out, char *in, const char *brkstr )
2060 {
2061         char    *str;
2062         char    *s;
2063         char    *lasts;
2064         int     i, j;
2065         char    **new;
2066
2067         /* find last element in list */
2068         for (i = 0; *out && (*out)[i]; i++);
2069
2070         /* protect the input string from strtok */
2071         str = ch_strdup( in );
2072
2073         if ( *str == '\0' ) {
2074                 free( str );
2075                 return( *out );
2076         }
2077
2078         /* Count words in string */
2079         j=1;
2080         for ( s = str; *s; s++ ) {
2081                 if ( strchr( brkstr, *s ) != NULL ) {
2082                         j++;
2083                 }
2084         }
2085
2086         *out = ch_realloc( *out, ( i + j + 1 ) * sizeof( char * ) );
2087         new = *out + i;
2088         for ( s = ldap_pvt_strtok( str, brkstr, &lasts );
2089                 s != NULL;
2090                 s = ldap_pvt_strtok( NULL, brkstr, &lasts ) )
2091         {
2092                 *new = ch_strdup( s );
2093                 new++;
2094         }
2095
2096         *new = NULL;
2097         free( str );
2098         return( *out );
2099 }
2100
2101 int config_generic_wrapper( Backend *be, const char *fname, int lineno,
2102         int argc, char **argv )
2103 {
2104         ConfigArgs c = { 0 };
2105         ConfigTable *ct;
2106         int rc;
2107
2108         c.be = be;
2109         c.fname = fname;
2110         c.lineno = lineno;
2111         c.argc = argc;
2112         c.argv = argv;
2113         c.valx = -1;
2114         c.line = line;
2115         c.op = SLAP_CONFIG_ADD;
2116         snprintf( c.log, sizeof( c.log ), "%s: line %d", fname, lineno );
2117
2118         rc = SLAP_CONF_UNKNOWN;
2119         ct = config_find_keyword( be->be_cf_ocs->co_table, &c );
2120         if ( ct ) {
2121                 c.table = be->be_cf_ocs->co_type;
2122                 rc = config_add_vals( ct, &c );
2123         }
2124         return rc;
2125 }
2126
2127 /* See if the given URL (in plain and parsed form) matches
2128  * any of the server's listener addresses. Return matching
2129  * Listener or NULL for no match.
2130  */
2131 Listener *config_check_my_url( const char *url, LDAPURLDesc *lud )
2132 {
2133         Listener **l = slapd_get_listeners();
2134         int i, isMe;
2135
2136         /* Try a straight compare with Listener strings */
2137         for ( i=0; l && l[i]; i++ ) {
2138                 if ( !strcasecmp( url, l[i]->sl_url.bv_val )) {
2139                         return l[i];
2140                 }
2141         }
2142
2143         isMe = 0;
2144         /* If hostname is empty, or is localhost, or matches
2145          * our hostname, this url refers to this host.
2146          * Compare it against listeners and ports.
2147          */
2148         if ( !lud->lud_host || !lud->lud_host[0] ||
2149                 !strncasecmp("localhost", lud->lud_host,
2150                         STRLENOF("localhost")) ||
2151                 !strcasecmp( global_host, lud->lud_host )) {
2152
2153                 for ( i=0; l && l[i]; i++ ) {
2154                         LDAPURLDesc *lu2;
2155                         ldap_url_parse( l[i]->sl_url.bv_val, &lu2 );
2156                         do {
2157                                 if ( strcasecmp( lud->lud_scheme,
2158                                         lu2->lud_scheme ))
2159                                         break;
2160                                 if ( lud->lud_port != lu2->lud_port )
2161                                         break;
2162                                 /* Listener on ANY address */
2163                                 if ( !lu2->lud_host || !lu2->lud_host[0] ) {
2164                                         isMe = 1;
2165                                         break;
2166                                 }
2167                                 /* URL on ANY address */
2168                                 if ( !lud->lud_host || !lud->lud_host[0] ) {
2169                                         isMe = 1;
2170                                         break;
2171                                 }
2172                                 /* Listener has specific host, must
2173                                  * match it
2174                                  */
2175                                 if ( !strcasecmp( lud->lud_host,
2176                                         lu2->lud_host )) {
2177                                         isMe = 1;
2178                                         break;
2179                                 }
2180                         } while(0);
2181                         ldap_free_urldesc( lu2 );
2182                         if ( isMe ) {
2183                                 return l[i];
2184                         }
2185                 }
2186         }
2187         return NULL;
2188 }