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