]> git.sur5r.net Git - openldap/blob - servers/slapd/slapcommon.c
Do not require ac/string.h for lber_pvt.h
[openldap] / servers / slapd / slapcommon.c
1 /* slapcommon.c - common routine for the slap tools */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2018 The OpenLDAP Foundation.
6  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7  * Portions Copyright 2003 IBM Corporation.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This work was initially developed by Kurt Zeilenga for inclusion
20  * in OpenLDAP Software.  Additional signficant contributors include
21  *    Jong Hyuk Choi
22  *    Hallvard B. Furuseth
23  *    Howard Chu
24  *    Pierangelo Masarati
25  */
26
27 #include "portable.h"
28
29 #include <stdio.h>
30
31 #include <ac/stdlib.h>
32 #include <ac/ctype.h>
33 #include <ac/string.h>
34 #include <ac/socket.h>
35 #include <ac/unistd.h>
36
37 #include "slapcommon.h"
38 #include "lutil.h"
39 #include "ldif.h"
40
41 tool_vars tool_globals;
42
43 #ifdef CSRIMALLOC
44 static char *leakfilename;
45 static FILE *leakfile;
46 #endif
47
48 static LDIFFP dummy;
49
50 #if defined(LDAP_SYSLOG) && defined(LDAP_DEBUG)
51 int start_syslog;
52 static char **syslog_unknowns;
53 #ifdef LOG_LOCAL4
54 static int syslogUser = SLAP_DEFAULT_SYSLOG_USER;
55 #endif /* LOG_LOCAL4 */
56 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
57
58 static void
59 usage( int tool, const char *progname )
60 {
61         char *options = NULL;
62         fprintf( stderr,
63                 "usage: %s [-v] [-d debuglevel] [-f configfile] [-F configdir] [-o <name>[=<value>]]",
64                 progname );
65
66         switch( tool ) {
67         case SLAPACL:
68                 options = "\n\t[-U authcID | -D authcDN] [-X authzID | -o authzDN=<DN>]"
69                         "\n\t-b DN [-u] [attr[/access][:value]] [...]\n";
70                 break;
71
72         case SLAPADD:
73                 options = " [-c]\n\t[-g] [-n databasenumber | -b suffix]\n"
74                         "\t[-l ldiffile] [-j linenumber] [-q] [-u] [-s] [-w]\n";
75                 break;
76
77         case SLAPAUTH:
78                 options = "\n\t[-U authcID] [-X authzID] [-R realm] [-M mech] ID [...]\n";
79                 break;
80
81         case SLAPCAT:
82                 options = " [-c]\n\t[-g] [-n databasenumber | -b suffix]"
83                         " [-l ldiffile] [-a filter] [-s subtree] [-H url]\n";
84                 break;
85
86         case SLAPDN:
87                 options = "\n\t[-N | -P] DN [...]\n";
88                 break;
89
90         case SLAPINDEX:
91                 options = " [-c]\n\t[-g] [-n databasenumber | -b suffix] [attr ...] [-q] [-t]\n";
92                 break;
93
94         case SLAPTEST:
95                 options = " [-n databasenumber] [-u] [-Q]\n";
96                 break;
97
98         case SLAPSCHEMA:
99                 options = " [-c]\n\t[-g] [-n databasenumber | -b suffix]"
100                         " [-l errorfile] [-a filter] [-s subtree] [-H url]\n";
101                 break;
102         }
103
104         if ( options != NULL ) {
105                 fputs( options, stderr );
106         }
107         exit( EXIT_FAILURE );
108 }
109
110 static int
111 parse_slapopt( int tool, int *mode )
112 {
113         size_t  len = 0;
114         char    *p;
115
116         p = strchr( optarg, '=' );
117         if ( p != NULL ) {
118                 len = p - optarg;
119                 p++;
120         }
121
122         if ( strncasecmp( optarg, "sockurl", len ) == 0 ) {
123                 if ( !BER_BVISNULL( &listener_url ) ) {
124                         ber_memfree( listener_url.bv_val );
125                 }
126                 ber_str2bv( p, 0, 1, &listener_url );
127
128         } else if ( strncasecmp( optarg, "domain", len ) == 0 ) {
129                 if ( !BER_BVISNULL( &peer_domain ) ) {
130                         ber_memfree( peer_domain.bv_val );
131                 }
132                 ber_str2bv( p, 0, 1, &peer_domain );
133
134         } else if ( strncasecmp( optarg, "peername", len ) == 0 ) {
135                 if ( !BER_BVISNULL( &peer_name ) ) {
136                         ber_memfree( peer_name.bv_val );
137                 }
138                 ber_str2bv( p, 0, 1, &peer_name );
139
140         } else if ( strncasecmp( optarg, "sockname", len ) == 0 ) {
141                 if ( !BER_BVISNULL( &sock_name ) ) {
142                         ber_memfree( sock_name.bv_val );
143                 }
144                 ber_str2bv( p, 0, 1, &sock_name );
145
146         } else if ( strncasecmp( optarg, "ssf", len ) == 0 ) {
147                 if ( lutil_atou( &ssf, p ) ) {
148                         Debug( LDAP_DEBUG_ANY, "unable to parse ssf=\"%s\".\n", p, 0, 0 );
149                         return -1;
150                 }
151
152         } else if ( strncasecmp( optarg, "transport_ssf", len ) == 0 ) {
153                 if ( lutil_atou( &transport_ssf, p ) ) {
154                         Debug( LDAP_DEBUG_ANY, "unable to parse transport_ssf=\"%s\".\n", p, 0, 0 );
155                         return -1;
156                 }
157
158         } else if ( strncasecmp( optarg, "tls_ssf", len ) == 0 ) {
159                 if ( lutil_atou( &tls_ssf, p ) ) {
160                         Debug( LDAP_DEBUG_ANY, "unable to parse tls_ssf=\"%s\".\n", p, 0, 0 );
161                         return -1;
162                 }
163
164         } else if ( strncasecmp( optarg, "sasl_ssf", len ) == 0 ) {
165                 if ( lutil_atou( &sasl_ssf, p ) ) {
166                         Debug( LDAP_DEBUG_ANY, "unable to parse sasl_ssf=\"%s\".\n", p, 0, 0 );
167                         return -1;
168                 }
169
170         } else if ( strncasecmp( optarg, "authzDN", len ) == 0 ) {
171                 ber_str2bv( p, 0, 1, &authzDN );
172
173 #if defined(LDAP_SYSLOG) && defined(LDAP_DEBUG)
174         } else if ( strncasecmp( optarg, "syslog", len ) == 0 ) {
175                 if ( parse_debug_level( p, &ldap_syslog, &syslog_unknowns ) ) {
176                         return -1;
177                 }
178                 start_syslog = 1;
179
180         } else if ( strncasecmp( optarg, "syslog-level", len ) == 0 ) {
181                 if ( parse_syslog_level( p, &ldap_syslog_level ) ) {
182                         return -1;
183                 }
184                 start_syslog = 1;
185
186 #ifdef LOG_LOCAL4
187         } else if ( strncasecmp( optarg, "syslog-user", len ) == 0 ) {
188                 if ( parse_syslog_user( p, &syslogUser ) ) {
189                         return -1;
190                 }
191                 start_syslog = 1;
192 #endif /* LOG_LOCAL4 */
193 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
194
195         } else if ( strncasecmp( optarg, "schema-check", len ) == 0 ) {
196                 switch ( tool ) {
197                 case SLAPADD:
198                         if ( strcasecmp( p, "yes" ) == 0 ) {
199                                 *mode &= ~SLAP_TOOL_NO_SCHEMA_CHECK;
200                         } else if ( strcasecmp( p, "no" ) == 0 ) {
201                                 *mode |= SLAP_TOOL_NO_SCHEMA_CHECK;
202                         } else {
203                                 Debug( LDAP_DEBUG_ANY, "unable to parse schema-check=\"%s\".\n", p, 0, 0 );
204                                 return -1;
205                         }
206                         break;
207
208                 default:
209                         Debug( LDAP_DEBUG_ANY, "schema-check meaningless for tool.\n", 0, 0, 0 );
210                         break;
211                 }
212
213         } else if ( strncasecmp( optarg, "value-check", len ) == 0 ) {
214                 switch ( tool ) {
215                 case SLAPADD:
216                         if ( strcasecmp( p, "yes" ) == 0 ) {
217                                 *mode |= SLAP_TOOL_VALUE_CHECK;
218                         } else if ( strcasecmp( p, "no" ) == 0 ) {
219                                 *mode &= ~SLAP_TOOL_VALUE_CHECK;
220                         } else {
221                                 Debug( LDAP_DEBUG_ANY, "unable to parse value-check=\"%s\".\n", p, 0, 0 );
222                                 return -1;
223                         }
224                         break;
225
226                 default:
227                         Debug( LDAP_DEBUG_ANY, "value-check meaningless for tool.\n", 0, 0, 0 );
228                         break;
229                 }
230
231         } else if ( ( strncasecmp( optarg, "ldif_wrap", len ) == 0 ) ||
232                         ( strncasecmp( optarg, "ldif-wrap", len ) == 0 ) ) {
233                 switch ( tool ) {
234                 case SLAPCAT:
235                         if ( strcasecmp( p, "no" ) == 0 ) {
236                                 ldif_wrap = LDIF_LINE_WIDTH_MAX;
237
238                         } else {
239                                 unsigned int u;
240                                 if ( lutil_atou( &u, p ) ) {
241                                         Debug( LDAP_DEBUG_ANY, "unable to parse ldif_wrap=\"%s\".\n", p, 0, 0 );
242                                         return -1;
243                                 }
244                                 ldif_wrap = (ber_len_t)u;
245                         }
246                         break;
247
248                 default:
249                         Debug( LDAP_DEBUG_ANY, "ldif-wrap meaningless for tool.\n", 0, 0, 0 );
250                         break;
251                 }
252
253         } else {
254                 return -1;
255         }
256
257         return 0;
258 }
259
260 /*
261  * slap_tool_init - initialize slap utility, handle program options.
262  * arguments:
263  *      name            program name
264  *      tool            tool code
265  *      argc, argv      command line arguments
266  */
267
268 static int need_shutdown;
269
270 void
271 slap_tool_init(
272         const char* progname,
273         int tool,
274         int argc, char **argv )
275 {
276         char *options;
277         char *conffile = NULL;
278         char *confdir = NULL;
279         struct berval base = BER_BVNULL;
280         char *filterstr = NULL;
281         char *subtree = NULL;
282         char *ldiffile  = NULL;
283         char **debug_unknowns = NULL;
284         int rc, i;
285         int mode = SLAP_TOOL_MODE;
286         int truncatemode = 0;
287         int use_glue = 1;
288         int writer;
289
290 #ifdef LDAP_DEBUG
291         /* tools default to "none", so that at least LDAP_DEBUG_ANY 
292          * messages show up; use -d 0 to reset */
293         slap_debug = LDAP_DEBUG_NONE;
294         ldif_debug = slap_debug;
295 #endif
296         ldap_syslog = 0;
297
298 #ifdef CSRIMALLOC
299         leakfilename = malloc( strlen( progname ) + STRLENOF( ".leak" ) + 1 );
300         sprintf( leakfilename, "%s.leak", progname );
301         if( ( leakfile = fopen( leakfilename, "w" )) == NULL ) {
302                 leakfile = stderr;
303         }
304         free( leakfilename );
305         leakfilename = NULL;
306 #endif
307
308         ldif_wrap = LDIF_LINE_WIDTH;
309
310         scope = LDAP_SCOPE_DEFAULT;
311
312         switch( tool ) {
313         case SLAPADD:
314                 options = "b:cd:f:F:gj:l:n:o:qsS:uvw";
315                 break;
316
317         case SLAPCAT:
318                 options = "a:b:cd:f:F:gH:l:n:o:s:v";
319                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
320                 break;
321
322         case SLAPDN:
323                 options = "d:f:F:No:Pv";
324                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
325                 break;
326
327         case SLAPMODIFY:
328                 options = "b:cd:f:F:gj:l:n:o:qsS:uvw";
329                 break;
330
331         case SLAPSCHEMA:
332                 options = "a:b:cd:f:F:gH:l:n:o:s:v";
333                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
334                 break;
335
336         case SLAPTEST:
337                 options = "d:f:F:n:o:Quv";
338                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
339                 break;
340
341         case SLAPAUTH:
342                 options = "d:f:F:M:o:R:U:vX:";
343                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
344                 break;
345
346         case SLAPINDEX:
347                 options = "b:cd:f:F:gn:o:qtv";
348                 mode |= SLAP_TOOL_READMAIN;
349                 break;
350
351         case SLAPACL:
352                 options = "b:D:d:f:F:o:uU:vX:";
353                 mode |= SLAP_TOOL_READMAIN | SLAP_TOOL_READONLY;
354                 break;
355
356         default:
357                 fprintf( stderr, "%s: unknown tool mode (%d)\n", progname, tool );
358                 exit( EXIT_FAILURE );
359         }
360
361         dbnum = -1;
362         while ( (i = getopt( argc, argv, options )) != EOF ) {
363                 switch ( i ) {
364                 case 'a':
365                         filterstr = ch_strdup( optarg );
366                         break;
367
368                 case 'b':
369                         ber_str2bv( optarg, 0, 1, &base );
370                         break;
371
372                 case 'c':       /* enable continue mode */
373                         continuemode++;
374                         break;
375
376                 case 'd': {     /* turn on debugging */
377                         int     level = 0;
378
379                         if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
380                                 usage( tool, progname );
381                         }
382 #ifdef LDAP_DEBUG
383                         if ( level == 0 ) {
384                                 /* allow to reset log level */
385                                 slap_debug = 0;
386
387                         } else {
388                                 slap_debug |= level;
389                         }
390 #else
391                         if ( level != 0 )
392                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
393                                        stderr );
394 #endif
395                         } break;
396
397                 case 'D':
398                         ber_str2bv( optarg, 0, 1, &authcDN );
399                         break;
400
401                 case 'f':       /* specify a conf file */
402                         conffile = ch_strdup( optarg );
403                         break;
404
405                 case 'F':       /* specify a conf dir */
406                         confdir = ch_strdup( optarg );
407                         break;
408
409                 case 'g':       /* disable subordinate glue */
410                         use_glue = 0;
411                         break;
412
413                 case 'H': {
414                         LDAPURLDesc *ludp;
415                         int rc;
416
417                         rc = ldap_url_parse_ext( optarg, &ludp,
418                                 LDAP_PVT_URL_PARSE_NOEMPTY_HOST | LDAP_PVT_URL_PARSE_NOEMPTY_DN );
419                         if ( rc != LDAP_URL_SUCCESS ) {
420                                 usage( tool, progname );
421                         }
422
423                         /* don't accept host, port, attrs, extensions */
424                         if ( ldap_pvt_url_scheme2proto( ludp->lud_scheme ) != LDAP_PROTO_TCP ) {
425                                 usage( tool, progname );
426                         }
427
428                         if ( ludp->lud_host != NULL ) {
429                                 usage( tool, progname );
430                         }
431
432                         if ( ludp->lud_port != 0 ) {
433                                 usage( tool, progname );
434                         }
435
436                         if ( ludp->lud_attrs != NULL ) {
437                                 usage( tool, progname );
438                         }
439
440                         if ( ludp->lud_exts != NULL ) {
441                                 usage( tool, progname );
442                         }
443
444                         if ( ludp->lud_dn != NULL && ludp->lud_dn[0] != '\0' ) {
445                                 ch_free( subtree );
446                                 subtree = ludp->lud_dn;
447                                 ludp->lud_dn = NULL;
448                         }
449
450                         if ( ludp->lud_filter != NULL && ludp->lud_filter[0] != '\0' ) {
451                                 filterstr = ludp->lud_filter;
452                                 ludp->lud_filter = NULL;
453                         }
454
455                         scope = ludp->lud_scope;
456
457                         ldap_free_urldesc( ludp );
458                         } break;
459
460                 case 'j':       /* jump to linenumber */
461                         if ( lutil_atoul( &jumpline, optarg ) ) {
462                                 usage( tool, progname );
463                         }
464                         break;
465
466                 case 'l':       /* LDIF file */
467                         ldiffile = ch_strdup( optarg );
468                         break;
469
470                 case 'M':
471                         ber_str2bv( optarg, 0, 0, &mech );
472                         break;
473
474                 case 'N':
475                         if ( dn_mode && dn_mode != SLAP_TOOL_LDAPDN_NORMAL ) {
476                                 usage( tool, progname );
477                         }
478                         dn_mode = SLAP_TOOL_LDAPDN_NORMAL;
479                         break;
480
481                 case 'n':       /* which config file db to index */
482                         if ( lutil_atoi( &dbnum, optarg ) || dbnum < 0 ) {
483                                 usage( tool, progname );
484                         }
485                         break;
486
487                 case 'o':
488                         if ( parse_slapopt( tool, &mode ) ) {
489                                 usage( tool, progname );
490                         }
491                         break;
492
493                 case 'P':
494                         if ( dn_mode && dn_mode != SLAP_TOOL_LDAPDN_PRETTY ) {
495                                 usage( tool, progname );
496                         }
497                         dn_mode = SLAP_TOOL_LDAPDN_PRETTY;
498                         break;
499
500                 case 'Q':
501                         quiet++;
502                         slap_debug = 0;
503                         break;
504
505                 case 'q':       /* turn on quick */
506                         mode |= SLAP_TOOL_QUICK;
507                         break;
508
509                 case 'R':
510                         realm = optarg;
511                         break;
512
513                 case 'S':
514                         if ( lutil_atou( &csnsid, optarg )
515                                 || csnsid > SLAP_SYNC_SID_MAX )
516                         {
517                                 usage( tool, progname );
518                         }
519                         break;
520
521                 case 's':
522                         switch ( tool ) {
523                         case SLAPADD:
524                         case SLAPMODIFY:
525                                 /* no schema check */
526                                 mode |= SLAP_TOOL_NO_SCHEMA_CHECK;
527                                 break;
528
529                         case SLAPCAT:
530                         case SLAPSCHEMA:
531                                 /* dump subtree */
532                                 ch_free( subtree );
533                                 subtree = ch_strdup( optarg );
534                                 break;
535                         }
536                         break;
537
538                 case 't':       /* turn on truncate */
539                         truncatemode++;
540                         mode |= SLAP_TRUNCATE_MODE;
541                         break;
542
543                 case 'U':
544                         ber_str2bv( optarg, 0, 0, &authcID );
545                         break;
546
547                 case 'u':       /* dry run */
548                         dryrun++;
549                         break;
550
551                 case 'v':       /* turn on verbose */
552                         verbose++;
553                         break;
554
555                 case 'w':       /* write context csn at the end */
556                         update_ctxcsn++;
557                         break;
558
559                 case 'X':
560                         ber_str2bv( optarg, 0, 0, &authzID );
561                         break;
562
563                 default:
564                         usage( tool, progname );
565                         break;
566                 }
567         }
568
569 #if defined(LDAP_SYSLOG) && defined(LDAP_DEBUG)
570         if ( start_syslog ) {
571                 char *logName;
572 #ifdef HAVE_EBCDIC
573                 logName = ch_strdup( progname );
574                 __atoe( logName );
575 #else
576                 logName = (char *)progname;
577 #endif
578
579 #ifdef LOG_LOCAL4
580                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
581 #elif defined LOG_DEBUG
582                 openlog( logName, OPENLOG_OPTIONS );
583 #endif
584 #ifdef HAVE_EBCDIC
585                 free( logName );
586                 logName = NULL;
587 #endif
588         }
589 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
590
591         switch ( tool ) {
592         case SLAPCAT:
593         case SLAPSCHEMA:
594                 writer = 1;
595                 break;
596
597         default:
598                 writer = 0;
599                 break;
600         }
601
602         switch ( tool ) {
603         case SLAPADD:
604         case SLAPCAT:
605         case SLAPMODIFY:
606         case SLAPSCHEMA:
607                 if ( ( argc != optind ) || (dbnum >= 0 && base.bv_val != NULL ) ) {
608                         usage( tool, progname );
609                 }
610
611                 break;
612
613         case SLAPINDEX:
614                 if ( dbnum >= 0 && base.bv_val != NULL ) {
615                         usage( tool, progname );
616                 }
617
618                 break;
619
620         case SLAPDN:
621                 if ( argc == optind ) {
622                         usage( tool, progname );
623                 }
624                 break;
625
626         case SLAPAUTH:
627                 if ( argc == optind && BER_BVISNULL( &authcID ) ) {
628                         usage( tool, progname );
629                 }
630                 break;
631
632         case SLAPTEST:
633                 if ( argc != optind ) {
634                         usage( tool, progname );
635                 }
636                 break;
637
638         case SLAPACL:
639                 if ( !BER_BVISNULL( &authcDN ) && !BER_BVISNULL( &authcID ) ) {
640                         usage( tool, progname );
641                 }
642                 if ( BER_BVISNULL( &base ) ) {
643                         usage( tool, progname );
644                 }
645                 ber_dupbv( &baseDN, &base );
646                 break;
647
648         default:
649                 break;
650         }
651
652         if ( ldiffile == NULL ) {
653                 dummy.fp = writer ? stdout : stdin;
654                 ldiffp = &dummy;
655
656         } else if ((ldiffp = ldif_open( ldiffile, writer ? "w" : "r" ))
657                 == NULL )
658         {
659                 perror( ldiffile );
660                 exit( EXIT_FAILURE );
661         }
662
663         /*
664          * initialize stuff and figure out which backend we're dealing with
665          */
666
667         rc = slap_init( mode, progname );
668         if ( rc != 0 ) {
669                 fprintf( stderr, "%s: slap_init failed!\n", progname );
670                 exit( EXIT_FAILURE );
671         }
672
673         rc = read_config( conffile, confdir );
674
675         if ( rc != 0 ) {
676                 fprintf( stderr, "%s: bad configuration %s!\n",
677                         progname, confdir ? "directory" : "file" );
678                 exit( EXIT_FAILURE );
679         }
680
681         if ( debug_unknowns ) {
682                 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
683                 ldap_charray_free( debug_unknowns );
684                 debug_unknowns = NULL;
685                 if ( rc )
686                         exit( EXIT_FAILURE );
687         }
688
689 #if defined(LDAP_SYSLOG) && defined(LDAP_DEBUG)
690         if ( syslog_unknowns ) {
691                 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
692                 ldap_charray_free( syslog_unknowns );
693                 syslog_unknowns = NULL;
694                 if ( rc )
695                         exit( EXIT_FAILURE );
696         }
697 #endif
698
699         at_oc_cache = 1;
700
701         switch ( tool ) {
702         case SLAPADD:
703         case SLAPCAT:
704         case SLAPINDEX:
705         case SLAPMODIFY:
706         case SLAPSCHEMA:
707                 if ( !nbackends ) {
708                         fprintf( stderr, "No databases found "
709                                         "in config file\n" );
710                         exit( EXIT_FAILURE );
711                 }
712                 break;
713
714         default:
715                 break;
716         }
717
718         if ( use_glue ) {
719                 rc = glue_sub_attach( 0 );
720
721                 if ( rc != 0 ) {
722                         fprintf( stderr,
723                                 "%s: subordinate configuration error\n", progname );
724                         exit( EXIT_FAILURE );
725                 }
726         }
727
728         rc = slap_schema_check();
729
730         if ( rc != 0 ) {
731                 fprintf( stderr, "%s: slap_schema_prep failed!\n", progname );
732                 exit( EXIT_FAILURE );
733         }
734
735         switch ( tool ) {
736         case SLAPTEST:
737                 if ( dbnum >= 0 )
738                         goto get_db;
739                 /* FALLTHRU */
740         case SLAPDN:
741         case SLAPAUTH:
742                 be = NULL;
743                 goto startup;
744
745         default:
746                 break;
747         }
748
749         if( filterstr ) {
750                 filter = str2filter( filterstr );
751
752                 if( filter == NULL ) {
753                         fprintf( stderr, "Invalid filter '%s'\n", filterstr );
754                         exit( EXIT_FAILURE );
755                 }
756
757                 ch_free( filterstr );
758                 filterstr = NULL;
759         }
760
761         if( subtree ) {
762                 struct berval val;
763                 ber_str2bv( subtree, 0, 0, &val );
764                 rc = dnNormalize( 0, NULL, NULL, &val, &sub_ndn, NULL );
765                 if( rc != LDAP_SUCCESS ) {
766                         fprintf( stderr, "Invalid subtree DN '%s'\n", subtree );
767                         exit( EXIT_FAILURE );
768                 }
769
770                 if ( BER_BVISNULL( &base ) && dbnum == -1 ) {
771                         base = val;
772                 } else {
773                         free( subtree );
774                         subtree = NULL;
775                 }
776         }
777
778         if( base.bv_val != NULL ) {
779                 struct berval nbase;
780
781                 rc = dnNormalize( 0, NULL, NULL, &base, &nbase, NULL );
782                 if( rc != LDAP_SUCCESS ) {
783                         fprintf( stderr, "%s: slap_init invalid suffix (\"%s\")\n",
784                                 progname, base.bv_val );
785                         exit( EXIT_FAILURE );
786                 }
787
788                 be = select_backend( &nbase, 0 );
789                 ber_memfree( nbase.bv_val );
790                 BER_BVZERO( &nbase );
791
792                 if( be == NULL ) {
793                         fprintf( stderr, "%s: slap_init no backend for \"%s\"\n",
794                                 progname, base.bv_val );
795                         exit( EXIT_FAILURE );
796                 }
797                 switch ( tool ) {
798                 case SLAPACL:
799                         goto startup;
800
801                 default:
802                         break;
803                 }
804
805                 /* If the named base is a glue master, operate on the
806                  * entire context
807                  */
808                 if ( SLAP_GLUE_INSTANCE( be ) ) {
809                         nosubordinates = 1;
810                 }
811
812                 ch_free( base.bv_val );
813                 BER_BVZERO( &base );
814
815         } else if ( dbnum == -1 ) {
816                 /* no suffix and no dbnum specified, just default to
817                  * the first available database
818                  */
819                 if ( nbackends <= 0 ) {
820                         fprintf( stderr, "No available databases\n" );
821                         exit( EXIT_FAILURE );
822                 }
823                 LDAP_STAILQ_FOREACH( be, &backendDB, be_next ) {
824                         dbnum++;
825
826                         /* db #0 is cn=config, don't select it as a default */
827                         if ( dbnum < 1 ) continue;
828                 
829                         if ( SLAP_MONITOR(be))
830                                 continue;
831
832                 /* If just doing the first by default and it is a
833                  * glue subordinate, find the master.
834                  */
835                         if ( SLAP_GLUE_SUBORDINATE(be) ) {
836                                 nosubordinates = 1;
837                                 continue;
838                         }
839                         break;
840                 }
841
842                 if ( !be ) {
843                         fprintf( stderr, "Available database(s) "
844                                         "do not allow %s\n", progname );
845                         exit( EXIT_FAILURE );
846                 }
847                 
848                 if ( nosubordinates == 0 && dbnum > 1 ) {
849                         Debug( LDAP_DEBUG_ANY,
850                                 "The first database does not allow %s;"
851                                 " using the first available one (%d)\n",
852                                 progname, dbnum, 0 );
853                 }
854
855         } else if ( dbnum >= nbackends ) {
856                 fprintf( stderr,
857                         "Database number selected via -n is out of range\n"
858                         "Must be in the range 0 to %d"
859                         " (the number of configured databases)\n",
860                         nbackends - 1 );
861                 exit( EXIT_FAILURE );
862
863         } else {
864 get_db:
865                 LDAP_STAILQ_FOREACH( be, &backendDB, be_next ) {
866                         if ( dbnum == 0 ) break;
867                         dbnum--;
868                 }
869         }
870
871         if ( scope != LDAP_SCOPE_DEFAULT && BER_BVISNULL( &sub_ndn ) ) {
872                 if ( be && be->be_nsuffix ) {
873                         ber_dupbv( &sub_ndn, be->be_nsuffix );
874
875                 } else {
876                         fprintf( stderr,
877                                 "<scope> needs a DN or a valid database\n" );
878                         exit( EXIT_FAILURE );
879                 }
880         }
881
882 startup:;
883         if ( be ) {
884                 BackendDB *bdtmp;
885
886                 dbnum = 0;
887                 LDAP_STAILQ_FOREACH( bdtmp, &backendDB, be_next ) {
888                         if ( bdtmp == be ) break;
889                         dbnum++;
890                 }
891         }
892
893 #ifdef CSRIMALLOC
894         mal_leaktrace(1);
895 #endif
896
897         if ( conffile != NULL ) {
898                 ch_free( conffile );
899                 conffile = NULL;
900         }
901
902         if ( confdir != NULL ) {
903                 ch_free( confdir );
904                 confdir = NULL;
905         }
906
907         if ( ldiffile != NULL ) {
908                 ch_free( ldiffile );
909                 ldiffile = NULL;
910         }
911
912         /* slapdn doesn't specify a backend to startup */
913         if ( !dryrun && tool != SLAPDN ) {
914                 need_shutdown = 1;
915
916                 if ( slap_startup( be ) ) {
917                         switch ( tool ) {
918                         case SLAPTEST:
919                                 fprintf( stderr, "slap_startup failed "
920                                                 "(test would succeed using "
921                                                 "the -u switch)\n" );
922                                 break;
923
924                         default:
925                                 fprintf( stderr, "slap_startup failed\n" );
926                                 break;
927                         }
928
929                         exit( EXIT_FAILURE );
930                 }
931         }
932 }
933
934 int slap_tool_destroy( void )
935 {
936         int rc = 0;
937         if ( !dryrun ) {
938                 if ( need_shutdown ) {
939                         if ( slap_shutdown( be ))
940                                 rc = EXIT_FAILURE;
941                 }
942                 if ( slap_destroy())
943                         rc = EXIT_FAILURE;
944         }
945 #ifdef SLAPD_MODULES
946         if ( slapMode == SLAP_SERVER_MODE ) {
947         /* always false. just pulls in necessary symbol references. */
948                 lutil_uuidstr(NULL, 0);
949         }
950         module_kill();
951 #endif
952         schema_destroy();
953 #ifdef HAVE_TLS
954         ldap_pvt_tls_destroy();
955 #endif
956         config_destroy();
957
958 #ifdef CSRIMALLOC
959         mal_dumpleaktrace( leakfile );
960 #endif
961
962         if ( !BER_BVISNULL( &authcDN ) ) {
963                 ch_free( authcDN.bv_val );
964                 BER_BVZERO( &authcDN );
965         }
966
967         if ( ldiffp && ldiffp != &dummy ) {
968                 ldif_close( ldiffp );
969         }
970         return rc;
971 }
972
973 int
974 slap_tool_update_ctxcsn(
975         const char *progname,
976         unsigned long sid,
977         struct berval *bvtext )
978 {
979         struct berval ctxdn;
980         ID ctxcsn_id;
981         Entry *ctxcsn_e;
982         int rc = EXIT_SUCCESS;
983
984         if ( !(update_ctxcsn && !dryrun && sid != SLAP_SYNC_SID_MAX + 1) ) {
985                 return rc;
986         }
987
988         if ( SLAP_SYNC_SUBENTRY( be )) {
989                 build_new_dn( &ctxdn, &be->be_nsuffix[0],
990                         (struct berval *)&slap_ldapsync_cn_bv, NULL );
991         } else {
992                 ctxdn = be->be_nsuffix[0];
993         }
994         ctxcsn_id = be->be_dn2id_get( be, &ctxdn );
995         if ( ctxcsn_id == NOID ) {
996                 if ( SLAP_SYNC_SUBENTRY( be )) {
997                         ctxcsn_e = slap_create_context_csn_entry( be, NULL );
998                         for ( sid = 0; sid <= SLAP_SYNC_SID_MAX; sid++ ) {
999                                 if ( maxcsn[ sid ].bv_len ) {
1000                                         attr_merge_one( ctxcsn_e, slap_schema.si_ad_contextCSN,
1001                                                 &maxcsn[ sid ], NULL );
1002                                 }
1003                         }
1004                         ctxcsn_id = be->be_entry_put( be, ctxcsn_e, bvtext );
1005                         if ( ctxcsn_id == NOID ) {
1006                                 fprintf( stderr, "%s: couldn't create context entry\n", progname );
1007                                 rc = EXIT_FAILURE;
1008                         }
1009                         entry_free( ctxcsn_e );
1010                 } else {
1011                         fprintf( stderr, "%s: context entry is missing\n", progname );
1012                         rc = EXIT_FAILURE;
1013                 }
1014         } else {
1015                 ctxcsn_e = be->be_entry_get( be, ctxcsn_id );
1016                 if ( ctxcsn_e != NULL ) {
1017                         Operation op = { 0 };
1018                         Entry *e = entry_dup( ctxcsn_e );
1019                         Attribute *attr = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
1020
1021                         int change;
1022                         op.o_bd = be;
1023                         be_entry_release_r( &op, ctxcsn_e );
1024
1025                         if ( attr ) {
1026                                 int             i;
1027
1028                                 change = 0;
1029
1030                                 for ( i = 0; !BER_BVISNULL( &attr->a_nvals[ i ] ); i++ ) {
1031                                         int rc_sid;
1032                                         int match;
1033                                         const char *text = NULL;
1034
1035                                         rc_sid = slap_parse_csn_sid( &attr->a_nvals[ i ] );
1036                                         if ( rc_sid < 0 ) {
1037                                                 Debug( LDAP_DEBUG_ANY,
1038                                                         "%s: unable to extract SID "
1039                                                         "from #%d contextCSN=%s\n",
1040                                                         progname, i,
1041                                                         attr->a_nvals[ i ].bv_val );
1042                                                 continue;
1043                                         }
1044
1045                                         assert( rc_sid <= SLAP_SYNC_SID_MAX );
1046
1047                                         sid = (unsigned)rc_sid;
1048
1049                                         if ( maxcsn[ sid ].bv_len == 0 ) {
1050                                                 match = -1;
1051
1052                                         } else {
1053                                                 value_match( &match, slap_schema.si_ad_entryCSN,
1054                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
1055                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1056                                                         &maxcsn[ sid ], &attr->a_nvals[i], &text );
1057                                         }
1058
1059                                         if ( match > 0 ) {
1060                                                 change = 1;
1061                                         } else {
1062                                                 AC_MEMCPY( maxcsn[ sid ].bv_val,
1063                                                         attr->a_nvals[ i ].bv_val,
1064                                                         attr->a_nvals[ i ].bv_len );
1065                                                 maxcsn[ sid ].bv_val[ attr->a_nvals[ i ].bv_len ] = '\0';
1066                                                 maxcsn[ sid ].bv_len = attr->a_nvals[ i ].bv_len;
1067                                         }
1068                                 }
1069
1070                                 if ( change ) {
1071                                         if ( attr->a_nvals != attr->a_vals ) {
1072                                                 ber_bvarray_free( attr->a_nvals );
1073                                         }
1074                                         attr->a_nvals = NULL;
1075                                         ber_bvarray_free( attr->a_vals );
1076                                         attr->a_vals = NULL;
1077                                         attr->a_numvals = 0;
1078                                 }
1079                         } else {
1080                                 change = 1;
1081                         }
1082
1083                         if ( change ) {
1084                                 for ( sid = 0; sid <= SLAP_SYNC_SID_MAX; sid++ ) {
1085                                         if ( maxcsn[ sid ].bv_len ) {
1086                                                 attr_merge_one( e, slap_schema.si_ad_contextCSN,
1087                                                         &maxcsn[ sid], NULL );
1088                                         }
1089                                 }
1090
1091                                 ctxcsn_id = be->be_entry_modify( be, e, bvtext );
1092                                 if( ctxcsn_id == NOID ) {
1093                                         fprintf( stderr, "%s: could not modify ctxcsn (%s)\n",
1094                                                 progname, bvtext->bv_val ? bvtext->bv_val : "" );
1095                                         rc = EXIT_FAILURE;
1096                                 } else if ( verbose ) {
1097                                         fprintf( stderr, "modified: \"%s\" (%08lx)\n",
1098                                                 e->e_dn, (long) ctxcsn_id );
1099                                 }
1100                         }
1101                         entry_free( e );
1102                 }
1103         } 
1104
1105         return rc;
1106 }
1107
1108 /*
1109  * return value:
1110  *      -1:                     update_ctxcsn == 0
1111  *      SLAP_SYNC_SID_MAX + 1:  unable to extract SID
1112  *      0 <= SLAP_SYNC_SID_MAX: the SID
1113  */
1114 unsigned long
1115 slap_tool_update_ctxcsn_check(
1116         const char *progname,
1117         Entry *e )
1118 {
1119         if ( update_ctxcsn ) {
1120                 unsigned long sid = SLAP_SYNC_SID_MAX + 1;
1121                 int rc_sid;
1122                 Attribute *attr;
1123
1124                 attr = attr_find( e->e_attrs, slap_schema.si_ad_entryCSN );
1125                 assert( attr != NULL );
1126
1127                 rc_sid = slap_parse_csn_sid( &attr->a_nvals[ 0 ] );
1128                 if ( rc_sid < 0 ) {
1129                         Debug( LDAP_DEBUG_ANY, "%s: could not "
1130                                 "extract SID from entryCSN=%s, entry dn=\"%s\"\n",
1131                                 progname, attr->a_nvals[ 0 ].bv_val, e->e_name.bv_val );
1132                         return (unsigned long)(-1);
1133
1134                 } else {
1135                         int match;
1136                         const char *text = NULL;
1137
1138                         assert( rc_sid <= SLAP_SYNC_SID_MAX );
1139
1140                         sid = (unsigned)rc_sid;
1141                         if ( maxcsn[ sid ].bv_len != 0 ) {
1142                                 match = 0;
1143                                 value_match( &match, slap_schema.si_ad_entryCSN,
1144                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
1145                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
1146                                         &maxcsn[ sid ], &attr->a_nvals[0], &text );
1147                         } else {
1148                                 match = -1;
1149                         }
1150                         if ( match < 0 ) {
1151                                 strcpy( maxcsn[ sid ].bv_val, attr->a_nvals[0].bv_val );
1152                                 maxcsn[ sid ].bv_len = attr->a_nvals[0].bv_len;
1153                         }
1154                 }
1155         }
1156
1157         return (unsigned long)(-1);
1158 }
1159
1160 int
1161 slap_tool_update_ctxcsn_init(void)
1162 {
1163         if ( update_ctxcsn ) {
1164                 unsigned long sid;
1165                 maxcsn[ 0 ].bv_val = maxcsnbuf;
1166                 for ( sid = 1; sid <= SLAP_SYNC_SID_MAX; sid++ ) {
1167                         maxcsn[ sid ].bv_val = maxcsn[ sid - 1 ].bv_val + LDAP_PVT_CSNSTR_BUFSIZE;
1168                         maxcsn[ sid ].bv_len = 0;
1169                 }
1170         }
1171
1172         return 0;
1173 }
1174
1175 int
1176 slap_tool_entry_check(
1177         const char *progname,
1178         Operation *op,
1179         Entry *e,
1180         int lineno,
1181         const char **text,
1182         char *textbuf,
1183         size_t textlen )
1184 {
1185         /* NOTE: we may want to conditionally enable manage */
1186         int manage = 0;
1187
1188         Attribute *oc = attr_find( e->e_attrs,
1189                 slap_schema.si_ad_objectClass );
1190
1191         if( oc == NULL ) {
1192                 fprintf( stderr, "%s: dn=\"%s\" (line=%d): %s\n",
1193                         progname, e->e_dn, lineno,
1194                         "no objectClass attribute");
1195                 return LDAP_NO_SUCH_ATTRIBUTE;
1196         }
1197
1198         /* check schema */
1199         op->o_bd = be;
1200
1201         if ( (slapMode & SLAP_TOOL_NO_SCHEMA_CHECK) == 0) {
1202                 int rc = entry_schema_check( op, e, NULL, manage, 1, NULL,
1203                         text, textbuf, textlen );
1204
1205                 if( rc != LDAP_SUCCESS ) {
1206                         fprintf( stderr, "%s: dn=\"%s\" (line=%d): (%d) %s\n",
1207                                 progname, e->e_dn, lineno, rc, *text );
1208                         return rc;
1209                 }
1210                 textbuf[ 0 ] = '\0';
1211         }
1212
1213         if ( (slapMode & SLAP_TOOL_VALUE_CHECK) != 0) {
1214                 Modifications *ml = NULL;
1215
1216                 int rc = slap_entry2mods( e, &ml, text, textbuf, textlen );
1217                 if ( rc != LDAP_SUCCESS ) {
1218                         fprintf( stderr, "%s: dn=\"%s\" (line=%d): (%d) %s\n",
1219                                 progname, e->e_dn, lineno, rc, *text );
1220                         return rc;
1221                 }
1222                 textbuf[ 0 ] = '\0';
1223
1224                 rc = slap_mods_check( op, ml, text, textbuf, textlen, NULL );
1225                 slap_mods_free( ml, 1 );
1226                 if ( rc != LDAP_SUCCESS ) {
1227                         fprintf( stderr, "%s: dn=\"%s\" (line=%d): (%d) %s\n",
1228                                 progname, e->e_dn, lineno, rc, *text );
1229                         return rc;
1230                 }
1231                 textbuf[ 0 ] = '\0';
1232         }
1233
1234         return LDAP_SUCCESS;
1235 }
1236