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