/*
 * Just a simple search client in C.  It does a ONELEVEL search, not a SUB
 * search, so provide the right FIND_DN for your FIND_FILTER.
 * 
 * I've tested this against NS LDAP SDK 3.0 and 4.1 for linux.
 * 
 * To build:
 * cc -I/tulsa/src/ldapsdk-30-Linux-ssl/include -L/tulsa/src/ldapsdk-30-Linux-ssl/lib -lldapssl30 -lpthread
 *
 * or
 *
 * cc -I/tulsa/src/ldapsdk-41-Linux_2.2.5-15-domestic-ssl/include -L/tulsa/src/ldapsdk-41-Linux_2.2.5-15-domestic-ssl/lib -lldapssl41 -lpthread
 *
 * Trevor Leffler
 * 07/16/2002
 */


#include <stdio.h>
#include <ldap.h>
#include <ldap_ssl.h>

/* Fill in the blanks for your LDAP environment */
#define LDAPS_SERVER	""
#define CERT7					""
#define BIND_DN				""
#define BIND_PW				""

#define FIND_DN				""
#define FIND_FILTER		""

int
main () {
	LDAP				*ld;
	LDAPMessage *result, *e;
	BerElement  *ber;
	char        *a, *dn;
	char        **vals;
	int         i, rc;

	if (ldapssl_client_init(CERT7, NULL) < 0) {
		printf("Failed to initialize SSL client...\n");
		return(1);
	}

	/* get a handle to an LDAP connection */
	if ( (ld = ldapssl_init(LDAPS_SERVER, LDAPS_PORT, 1)) == NULL) {
		perror("ldapssl_init");
		return(1);
	}

	/* authenticate */
	rc = ldap_simple_bind_s(ld, BIND_DN, BIND_PW);
	if (rc != LDAP_SUCCESS) {
		fprintf(stderr, "ldap_simple_bind_s: [%d] %s\n", rc, ldap_err2string(rc));
		return(1);
	}

	/* search for the entry */
	if ( (rc = ldap_search_ext_s(ld, FIND_DN, LDAP_SCOPE_ONELEVEL, FIND_FILTER,
		NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result)) != LDAP_SUCCESS ) {
		fprintf(stderr, "ldap_search_ext_s: %s\n", ldap_err2string(rc));
		return(1);
	}

	/* Since we are doing a onelevel search, there should be only one
	 * matching entry
	 */
	e = ldap_first_entry(ld, result);
	if (e != NULL) {
		printf("\nFound %s:\n\n", FIND_DN);

		/* Iterate through each attribute in the entry. */
		for (a = ldap_first_attribute(ld, e, &ber); a != NULL; a = ldap_next_attribute(ld, e, ber)) {
			/* For each attribute, print the attribute name and values. */
			if ((vals = ldap_get_values(ld, e, a)) != NULL) {
				for(i = 0; vals[i] != NULL; i++) {
					printf("%s: %s\n", a, vals[i]);
				}
				ldap_value_free(vals);
			}

			ldap_memfree(a);
		}

		if (ber != NULL) {
			ber_free(ber, 0);
		}
	}

	ldap_msgfree(result);
	ldap_unbind(ld);
	return(0);
}
