1/*	$NetBSD: ftest.c,v 1.1.1.3 2010/12/12 15:21:31 adam Exp $	*/
2
3/* ftest.c -- OpenLDAP Filter API Test */
4/* OpenLDAP: pkg/ldap/libraries/libldap/ftest.c,v 1.15.2.5 2010/04/13 20:22:57 kurt Exp */
5/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
6 *
7 * Copyright 1998-2010 The OpenLDAP Foundation.
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 the file LICENSE in the
15 * top-level directory of the distribution or, alternatively, at
16 * <http://www.OpenLDAP.org/license.html>.
17 */
18
19#include "portable.h"
20
21#include <ac/stdlib.h>
22#include <ac/string.h>
23#include <ac/unistd.h>
24
25#include <stdio.h>
26
27#include <ldap.h>
28
29#include "ldap_pvt.h"
30#include "lber_pvt.h"
31
32#include "ldif.h"
33#include "lutil.h"
34#include "lutil_ldap.h"
35#include "ldap_defaults.h"
36
37static int filter2ber( char *filter );
38
39int usage()
40{
41	fprintf( stderr, "usage:\n"
42		"  ftest [-d n] filter\n"
43		"    filter - RFC 4515 string representation of an "
44			"LDAP search filter\n" );
45	return EXIT_FAILURE;
46}
47
48int
49main( int argc, char *argv[] )
50{
51	int c;
52	int debug=0;
53
54    while( (c = getopt( argc, argv, "d:" )) != EOF ) {
55		switch ( c ) {
56		case 'd':
57			debug = atoi( optarg );
58			break;
59		default:
60			fprintf( stderr, "ftest: unrecognized option -%c\n",
61				optopt );
62			return usage();
63		}
64	}
65
66	if ( debug ) {
67		if ( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
68			!= LBER_OPT_SUCCESS )
69		{
70			fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n",
71				debug );
72		}
73		if ( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
74			!= LDAP_OPT_SUCCESS )
75		{
76			fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n",
77				debug );
78		}
79	}
80
81	if ( argc - optind != 1 ) {
82		return usage();
83	}
84
85	return filter2ber( strdup( argv[optind] ) );
86}
87
88static int filter2ber( char *filter )
89{
90	int rc;
91	struct berval bv = BER_BVNULL;
92	BerElement *ber;
93
94	printf( "Filter: %s\n", filter );
95
96	ber = ber_alloc_t( LBER_USE_DER );
97	if( ber == NULL ) {
98		perror( "ber_alloc_t" );
99		return EXIT_FAILURE;
100	}
101
102	rc = ldap_pvt_put_filter( ber, filter );
103	if( rc < 0 ) {
104		fprintf( stderr, "Filter error!\n");
105		return EXIT_FAILURE;
106	}
107
108	rc = ber_flatten2( ber, &bv, 0 );
109	if( rc < 0 ) {
110		perror( "ber_flatten2" );
111		return EXIT_FAILURE;
112	}
113
114	printf( "BER encoding (len=%ld):\n", (long) bv.bv_len );
115	ber_bprint( bv.bv_val, bv.bv_len );
116
117	ber_free( ber, 1 );
118
119	return EXIT_SUCCESS;
120}
121
122