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