int main(void){ char searchstring[55]; char *rfid_number; char *uid; rfid_number=readRFID(); if(DATABASE == 1) { snprintf(searchstring,55,"(pager=%s)",rfid_number); uid = ldap_search(searchstring,"uid"); if(!strcmp(uid,"failed")){ printf("Fehlgeschlagen!\r\n"); return 0; } }else if(DATABASE == 2) { snprintf(searchstring,55,"SELECT uid FROM account WHERE rfid='%s';",rfid_number); if(sql_search(searchstring)){ printf("Something was wrong"); } } //free(uid); free(rfid_number); return 0; }
static krb5_error_code LDAP_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry) { krb5_error_code ret; int msgid; ret = LDAP__connect(context, db); if (ret) return ret; ret = LDAP_no_size_limit(context, HDB2LDAP(db)); if (ret) return ret; msgid = ldap_search(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE, "(|(objectClass=krb5Principal)(objectClass=sambaSamAccount))", krb5kdcentry_attrs, 0); if (msgid < 0) return HDB_ERR_NOENTRY; HDBSETMSGID(db, msgid); return LDAP_seq(context, db, flags, entry); }
int ldap_search_st( LDAP *ld, LDAP_CONST char *base, int scope, LDAP_CONST char *filter, char **attrs, int attrsonly, struct timeval *timeout, LDAPMessage **res ) { int msgid; *res = NULL; if ( (msgid = ldap_search( ld, base, scope, filter, attrs, attrsonly )) == -1 ) return( ld->ld_errno ); if ( ldap_result( ld, msgid, LDAP_MSG_ALL, timeout, res ) == -1 || !*res ) return( ld->ld_errno ); if ( ld->ld_errno == LDAP_TIMEOUT ) { (void) ldap_abandon( ld, msgid ); ld->ld_errno = LDAP_TIMEOUT; return( ld->ld_errno ); } return( ldap_result2error( ld, *res, 0 ) ); }
/* ARGSUSED */ int _ns_ldap_search(char *service, int flags, char *base, int scope, char *filter, char **attrs, int attrsonly) { LDAP *ld = __s_api_getLDAPconn(flags); return (ldap_search(ld, base, scope, filter, attrs, attrsonly)); }
// Fetch all attributes of an entry, and display them in a dialog void LdapView::showProperties( LDAP *ld, char *dn ) { PropDlg dlg; if ( ldap_search( ld, dn, LDAP_SCOPE_BASE, "objectclass=*", NULL, FALSE ) == -1 ) { AfxMessageBox( "Failed to start asynchronous search" ); return; } LDAPMessage *res; int rc; // Process results as they come in while ( (rc = ldap_result( ld, LDAP_RES_ANY, 0, NULL, &res )) == LDAP_RES_SEARCH_ENTRY ) { LDAPMessage *e = ldap_first_entry( ld, res ); BerElement *ber; // Loop over attributes in this entry for ( char *a = ldap_first_attribute( ld, e, &ber ); a != NULL; a = ldap_next_attribute( ld, e, ber ) ) { struct berval **bvals; if ( (bvals = ldap_get_values_len( ld, e, a )) != NULL ) { dlg.AddLine( a ); // Loop over values for this attribute for ( int i = 0; bvals[i] != NULL; i++ ) { CString val; val.Format( " %s", bvals[ i ]->bv_val ); dlg.AddLine( val ); } ber_bvecfree( bvals ); } } if ( ber != NULL ) ber_free( ber, 0 ); ldap_msgfree( res ); } if ( rc == -1 ) { AfxMessageBox( "Error on ldap_result" ); return; } else if (( rc = ldap_result2error( ld, res, 0 )) != LDAP_SUCCESS ) { char *errString = ldap_err2string( rc ); AfxMessageBox( errString ); } ldap_msgfree( res ); // Set the title of the dialog to the distinguished name, and display it dlg.SetTitle( dn ); dlg.DoModal(); }
/* * Returns an LDAP error code. */ static int cmp2( LDAP *ld1, LDAP *ld2, LDAPMessage *e1, int findonly) { LDAPMessage *e2, *res; char *dn, *attrcmp; int found=0, rc; ATTR *a1, *a2; dn = ldap_get_dn( ld1, e1 ); if ( ldaptool_verbose ) { if ( findonly ) { printf( "Checking that %s exists on both servers\n", dn ); } else { printf("Comparing entry %s on both servers\n", dn ); } } if ( ldap_search( ld2, dn, LDAP_SCOPE_BASE, "objectClass=*", NULL, 0 ) == -1 ) { return( ldaptool_print_lderror( ld2, "ldap_search", LDAPTOOL_CHECK4SSL_IF_APPROP )); } /* XXXmcs: this code should be modified to display referrals and references */ while ( (rc = ldap_result( ld2, LDAP_RES_ANY, 0, NULL, &res )) == LDAP_RES_SEARCH_ENTRY ) { e2 = ldap_first_entry( ld1, res ); found = 1; if ( !findonly ) { a1 = get_attrs( ld1, e1 ); a2 = get_attrs( ld2, e2 ); attrcmp = cmp_attrs( a1, a2 ); if ( strcmp( attrcmp, "") != 0 ) { printf("\n%s%s\n", dn, attrcmp); } } ldap_msgfree( res ); } if ( !found ) { notfound( dn, findonly ); differ = 1; } if ( rc == -1 ) { return( ldaptool_print_lderror( ld2, "ldap_result", LDAPTOOL_CHECK4SSL_IF_APPROP )); } ldap_msgfree( res ); ldap_memfree( dn ); return(rc); }
int ldap_search_s( LDAP *ld, char *base, int scope, char *filter, char **attrs, int attrsonly, LDAPMessage **res ) { int msgid; if ( (msgid = ldap_search( ld, base, scope, filter, attrs, attrsonly )) == -1 ) return( ld->ld_errno ); if ( ldap_result( ld, msgid, 1, (struct timeval *) NULL, res ) == -1 ) return( ld->ld_errno ); return( ldap_result2error( ld, *res, 0 ) ); }
void read_cb(ev_loop *loop, ev_io *watcher, int revents) { char buf[BUF_SIZE]; ssize_t buf_cnt; LDAPMessage_t *req = NULL; asn_dec_rval_t rdecode; if (EV_ERROR & revents) fail("got invalid event"); bzero(buf, sizeof(buf)); buf_cnt = recv(watcher->fd, buf, sizeof(buf), 0); if (buf_cnt <= 0) { ev_close(loop, watcher); if (buf_cnt < 0) fail("read"); return; } /* from asn1c's FAQ: If you want data to be BER or DER encoded, just invoke der_encode(). */ rdecode = asn_DEF_LDAPMessage.ber_decoder(0, &asn_DEF_LDAPMessage, (void **)&req, buf, buf_cnt, 0); if (rdecode.code != RC_OK || (ssize_t) rdecode.consumed != buf_cnt) { ev_close(loop, watcher); ldapmessage_free(req); fail((rdecode.code != RC_OK) ? "der_decoder" : "consumed"); } LDAP_DEBUG(req); switch (req->protocolOp.present) { case LDAPMessage__protocolOp_PR_bindRequest: ldap_bind(req->messageID, &req->protocolOp.choice.bindRequest, loop, watcher); break; case LDAPMessage__protocolOp_PR_searchRequest: ldap_search(req->messageID, &req->protocolOp.choice.searchRequest, loop, watcher); break; case LDAPMessage__protocolOp_PR_unbindRequest: ev_close(loop, watcher); break; default: perror("_|_"); ev_close(loop, watcher); } ldapmessage_free(req); }
int abook_ldap_searchstart(abook_ldap_state **ldap_state, abook_fielddata *flist, int fcount) { abook_ldap_state *mystate; int msgid, rc; int sizelimit; char *msg; char *attrs[20]; LDAP *ld; LDAPMessage *result; char *filter, *secondaryfilter; int searching_secondary = 0; if (config_ldap() < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to configure LDAP"); return -1; } if (imsp_to_ldap_filter(flist, fcount, &filter, config) < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to convert filter"); return -1; } ld = ldap_init(config.ldaphost, config.ldapport); if (ld == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP init failed: %s", strerror(errno)); return -1; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_searchstart: simple bind failed: %s", ldap_err2string(rc)); return -1; } /* For testing the error handlers... sizelimit = 4; ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &sizelimit); */ attrs[0] = config.fullnameattr; attrs[1] = config.uniqueattr; attrs[2] = NULL; msgid = ldap_search(ld, config.searchbase, config.scope, filter, attrs, 0/*attrs-only*/); if (msgid == -1) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP search failed"); ldap_unbind(ld); return -1; } rc = ldap_result(ld, msgid, 0, NULL, &result); switch (rc) { case LDAP_RES_SEARCH_ENTRY: /* Do nothing here. The abook_search function will pull out this * entry and send it back for display to the user. * The result is freed later. */ break; case LDAP_RES_SEARCH_RESULT: rc = ldap_result2error(ld, result, 1 /* free result */); if (rc == LDAP_SUCCESS) { /* * Search returned successfully, but with no matching entries. * * Try to do the secondary search, if configured to do so. * fails, then set the prevresult to NULL. */ if (secondaryconfig.ldaphost) { searching_secondary = 1; /* close the connection to the primary ldap server */ ldap_unbind(ld); if (imsp_to_ldap_filter(flist, fcount, &secondaryfilter, secondaryconfig) < 0) { syslog(LOG_ERR, "abook_ldap_searchstart: failed to convert filter"); return -1; } /* open connection to the secondary server */ ld = ldap_init(secondaryconfig.ldaphost, secondaryconfig.ldapport); if (ld == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP init failed: %s", strerror(errno)); return -1; } rc = ldap_simple_bind_s(ld, NULL, NULL); if (rc != LDAP_SUCCESS) { syslog(LOG_ERR, "abook_ldap_searchstart: simple bind failed: %s", ldap_err2string(rc)); return -1; } attrs[0] = secondaryconfig.fullnameattr; attrs[1] = secondaryconfig.uniqueattr; attrs[2] = NULL; msgid = ldap_search(ld, secondaryconfig.searchbase, secondaryconfig.scope, secondaryfilter, attrs, 0 /*attrs-only*/); if (msgid == -1) { syslog(LOG_ERR, "abook_ldap_searchstart: LDAP search failed"); ldap_unbind(ld); return -1; } rc = ldap_result(ld, msgid, 0, NULL, &result); switch (rc) { case LDAP_RES_SEARCH_ENTRY: /* Do nothing here. The abook_search function will pull out this * entry and send it back for display to the user. * The result is freed later. */ break; case LDAP_RES_SEARCH_RESULT: /* Still didn't get any data. Send a null "prevresult" to the * abook_search function. */ result = NULL; break; default: syslog(LOG_ERR, "abook_ldap_searchstart: ldap_result failed: %s (%d)", ldap_err2string(rc), rc); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } } /* if (secondaryconfig.ldaphost) */ } else { syslog(LOG_ERR,"abook_ldap_searchstart: search returned error: %s", ldap_err2string(rc)); ldap_unbind(ld); return -1; } break; default: syslog(LOG_ERR, "abook_ldap_searchstart: ldap_result failed: A1 SEARCHADDRESS %s", ldap_err2string(rc)); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } mystate = (abook_ldap_state *) malloc (sizeof (abook_ldap_state)); *ldap_state = mystate; if (mystate == NULL) { syslog(LOG_ERR, "abook_ldap_searchstart: Out of memory"); (void) ldap_msgfree(result); /* ignore message type return value */ ldap_unbind(ld); return -1; } mystate->ld = ld; mystate->msgid = msgid; mystate->prevresult = result; if (searching_secondary == 0) { mystate->ldapconfig = &config; } else { mystate->ldapconfig = &secondaryconfig; } return 0; }
int cldap_search_s( LDAP *ld, char *base, int scope, char *filter, char **attrs, int attrsonly, LDAPMessage **res, char *logdn ) { int ret, msgid; struct cldap_retinfo cri; *res = NULLMSG; (void) memset( &cri, 0, sizeof( cri )); #if defined( SUN ) && defined( _REENTRANT ) LOCK_LDAP(ld); #endif if ( logdn != NULL ) { ld->ld_cldapdn = logdn; } else if ( ld->ld_cldapdn == NULL ) { ld->ld_cldapdn = ""; } do { if ( cri.cri_try != 0 ) { --ld->ld_msgid; /* use same id as before */ } ld->ld_sb.sb_useaddr = ld->ld_sb.sb_addrs[ cri.cri_useaddr ]; Debug( LDAP_DEBUG_TRACE, catgets(slapdcat, 1, 115, "cldap_search_s try %1$d (to %2$s)\n"), cri.cri_try, inet_ntoa( ((struct sockaddr_in *) ld->ld_sb.sb_useaddr)->sin_addr ), 0 ); if ( (msgid = ldap_search( ld, base, scope, filter, attrs, attrsonly )) == -1 ) { #if defined( SUN ) && defined( _REENTRANT ) UNLOCK_LDAP(ld); #endif return( ld->ld_errno ); } #ifndef NO_CACHE #if defined( SUN ) && defined( _REENTRANT ) LOCK_RESPONSE(ld); #endif if ( ld->ld_cache != NULL && ld->ld_responses != NULL ) { Debug( LDAP_DEBUG_TRACE, catgets(slapdcat, 1, 116, "cldap_search_s res from cache\n"), 0, 0, 0 ); *res = ld->ld_responses; ld->ld_responses = ld->ld_responses->lm_next; #if defined( SUN ) && defined( _REENTRANT ) UNLOCK_LDAP(ld); ret = ldap_result2error( ld, *res, 0 ); UNLOCK_RESPONSE(ld); return( ret ); #else return( ldap_result2error( ld, *res, 0 )); #endif } #endif /* NO_CACHE */ ret = cldap_result( ld, msgid, res, &cri, base ); #if defined( SUN ) && defined( _REENTRANT ) UNLOCK_RESPONSE(ld); #endif } while (ret == -1); return( ret ); }
#include <stdio.h> #include <ctype.h> #include <string.h> #ifdef MACOS #include <stdlib.h> #ifdef THINK_C #include <console.h> #include <unix.h> #include <fcntl.h> #endif /* THINK_C */ #include "macos.h" #else /* MACOS */ #if defined( DOS ) || defined( _WIN32 ) #ifdef DOS #include "msdos.h" #endif #if defined( WINSOCK ) || defined( _WIN32 ) #include "console.h" #endif /* WINSOCK */ #else /* DOS */ #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/file.h> #ifndef VMS #include <fcntl.h> #include <unistd.h> #endif /* VMS */ #endif /* DOS */ #endif /* MACOS */ #include "lber.h" #include "ldap.h" #if !defined( PCNFS ) && !defined( WINSOCK ) && !defined( MACOS ) #define MOD_USE_BVALS #endif /* !PCNFS && !WINSOCK && !MACOS */ #ifdef NEEDPROTOS static void handle_result( LDAP *ld, LDAPMessage *lm ); static void print_ldap_result( LDAP *ld, LDAPMessage *lm, char *s ); static void print_search_entry( LDAP *ld, LDAPMessage *res ); static void free_list( char **list ); #else static void handle_result(); static void print_ldap_result(); static void print_search_entry(); static void free_list(); #endif /* NEEDPROTOS */ #define NOCACHEERRMSG \ "don't compile with -DNO_CACHE if you desire local caching" char *dnsuffix; #ifndef WINSOCK static char * getline( char *line, int len, FILE *fp, char *prompt ) { printf(prompt); if ( fgets( line, len, fp ) == NULL ) return( NULL ); line[ strlen( line ) - 1 ] = '\0'; return( line ); } #endif /* WINSOCK */ static char ** get_list( char *prompt ) { static char buf[256]; int num; char **result; num = 0; result = (char **) 0; while ( 1 ) { getline( buf, sizeof(buf), stdin, prompt ); if ( *buf == '\0' ) break; if ( result == (char **) 0 ) result = (char **) malloc( sizeof(char *) ); else result = (char **) realloc( result, sizeof(char *) * (num + 1) ); result[num++] = (char *) strdup( buf ); } if ( result == (char **) 0 ) return( NULL ); result = (char **) realloc( result, sizeof(char *) * (num + 1) ); result[num] = NULL; return( result ); } static void free_list( char **list ) { int i; if ( list != NULL ) { for ( i = 0; list[ i ] != NULL; ++i ) { free( list[ i ] ); } free( (char *)list ); } } #ifdef MOD_USE_BVALS static int file_read( char *path, struct berval *bv ) { FILE *fp; long rlen; int eof; if (( fp = fopen( path, "r" )) == NULL ) { perror( path ); return( -1 ); } if ( fseek( fp, 0L, SEEK_END ) != 0 ) { perror( path ); fclose( fp ); return( -1 ); } bv->bv_len = ftell( fp ); if (( bv->bv_val = (char *)malloc( bv->bv_len )) == NULL ) { perror( "malloc" ); fclose( fp ); return( -1 ); } if ( fseek( fp, 0L, SEEK_SET ) != 0 ) { perror( path ); fclose( fp ); return( -1 ); } rlen = fread( bv->bv_val, 1, bv->bv_len, fp ); eof = feof( fp ); fclose( fp ); if ( rlen != bv->bv_len ) { perror( path ); free( bv->bv_val ); return( -1 ); } return( bv->bv_len ); } #endif /* MOD_USE_BVALS */ static LDAPMod ** get_modlist( char *prompt1, char *prompt2, char *prompt3 ) { static char buf[256]; int num; LDAPMod tmp; LDAPMod **result; #ifdef MOD_USE_BVALS struct berval **bvals; #endif /* MOD_USE_BVALS */ num = 0; result = NULL; while ( 1 ) { if ( prompt1 ) { getline( buf, sizeof(buf), stdin, prompt1 ); tmp.mod_op = atoi( buf ); if ( tmp.mod_op == -1 || buf[0] == '\0' ) break; } getline( buf, sizeof(buf), stdin, prompt2 ); if ( buf[0] == '\0' ) break; tmp.mod_type = strdup( buf ); tmp.mod_values = get_list( prompt3 ); #ifdef MOD_USE_BVALS if ( tmp.mod_values != NULL ) { int i; for ( i = 0; tmp.mod_values[i] != NULL; ++i ) ; bvals = (struct berval **)calloc( i + 1, sizeof( struct berval *)); for ( i = 0; tmp.mod_values[i] != NULL; ++i ) { bvals[i] = (struct berval *)malloc( sizeof( struct berval )); if ( strncmp( tmp.mod_values[i], "{FILE}", 6 ) == 0 ) { if ( file_read( tmp.mod_values[i] + 6, bvals[i] ) < 0 ) { return( NULL ); } } else { bvals[i]->bv_val = tmp.mod_values[i]; bvals[i]->bv_len = strlen( tmp.mod_values[i] ); } } tmp.mod_bvalues = bvals; tmp.mod_op |= LDAP_MOD_BVALUES; } #endif /* MOD_USE_BVALS */ if ( result == NULL ) result = (LDAPMod **) malloc( sizeof(LDAPMod *) ); else result = (LDAPMod **) realloc( result, sizeof(LDAPMod *) * (num + 1) ); result[num] = (LDAPMod *) malloc( sizeof(LDAPMod) ); *(result[num]) = tmp; /* struct copy */ num++; } if ( result == NULL ) return( NULL ); result = (LDAPMod **) realloc( result, sizeof(LDAPMod *) * (num + 1) ); result[num] = NULL; return( result ); } #ifdef LDAP_REFERRALS int bind_prompt( LDAP *ld, char **dnp, char **passwdp, int *authmethodp, int freeit ) { static char dn[256], passwd[256]; if ( !freeit ) { #ifdef KERBEROS getline( dn, sizeof(dn), stdin, "re-bind method (0->simple, " "1->krbv41, 2->krbv42, 3->krbv41&2)? " ); if (( *authmethodp = atoi( dn )) == 3 ) { *authmethodp = LDAP_AUTH_KRBV4; } else { *authmethodp |= 0x80; } #else /* KERBEROS */ *authmethodp = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "re-bind dn? " ); strcat( dn, dnsuffix ); *dnp = dn; if ( *authmethodp == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) { getline( passwd, sizeof(passwd), stdin, "re-bind password? " ); } else { passwd[0] = '\0'; } *passwdp = passwd; } return( LDAP_SUCCESS ); } #endif /* LDAP_REFERRALS */ int #ifdef WINSOCK ldapmain( #else /* WINSOCK */ main( #endif /* WINSOCK */ int argc, char **argv ) { LDAP *ld; int i, c, port, cldapflg, errflg, method, id, msgtype; char line[256], command1, command2, command3; char passwd[64], dn[256], rdn[64], attr[64], value[256]; char filter[256], *host, **types; char **exdn; char *usage = "usage: %s [-u] [-h host] [-d level] " "[-s dnsuffix] [-p port] [-t file] [-T file]\n"; int bound, all, scope, attrsonly; LDAPMessage *res; LDAPMod **mods, **attrs; struct timeval timeout; char *copyfname = NULL; int copyoptions = 0; LDAPURLDesc *ludp; extern char *optarg; extern int optind; #ifdef MACOS if (( argv = get_list( "cmd line arg?" )) == NULL ) { exit( 1 ); } for ( argc = 0; argv[ argc ] != NULL; ++argc ) { ; } #endif /* MACOS */ host = NULL; port = LDAP_PORT; dnsuffix = ""; cldapflg = errflg = 0; while (( c = getopt( argc, argv, "uh:d:s:p:t:T:" )) != -1 ) { switch( c ) { case 'u': #ifdef CLDAP cldapflg++; #else /* CLDAP */ printf( "Compile with -DCLDAP for UDP support\n" ); #endif /* CLDAP */ break; case 'd': #ifdef LDAP_DEBUG ldap_debug = atoi( optarg ); if ( ldap_debug & LDAP_DEBUG_PACKETS ) { lber_debug = ldap_debug; } #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'h': host = optarg; break; case 's': dnsuffix = optarg; break; case 'p': port = atoi( optarg ); break; #if !defined(MACOS) && !defined(DOS) case 't': /* copy ber's to given file */ copyfname = strdup( optarg ); copyoptions = LBER_TO_FILE; break; case 'T': /* only output ber's to given file */ copyfname = strdup( optarg ); copyoptions = (LBER_TO_FILE | LBER_TO_FILE_ONLY); break; #endif default: ++errflg; } } if ( host == NULL && optind == argc - 1 ) { host = argv[ optind ]; ++optind; } if ( errflg || optind < argc - 1 ) { fprintf( stderr, usage, argv[ 0 ] ); exit( 1 ); } printf( "%sldap_open( %s, %d )\n", cldapflg ? "c" : "", host == NULL ? "(null)" : host, port ); if ( cldapflg ) { #ifdef CLDAP ld = cldap_open( host, port ); #endif /* CLDAP */ } else { ld = ldap_open( host, port ); } if ( ld == NULL ) { perror( "ldap_open" ); exit(1); } #if !defined(MACOS) && !defined(DOS) if ( copyfname != NULL ) { if ( (ld->ld_sb.sb_fd = open( copyfname, O_WRONLY | O_CREAT, 0600 )) == -1 ) { perror( copyfname ); exit ( 1 ); } ld->ld_sb.sb_options = copyoptions; } #endif bound = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; (void) memset( line, '\0', sizeof(line) ); while ( getline( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) { command1 = line[0]; command2 = line[1]; command3 = line[2]; switch ( command1 ) { case 'a': /* add or abandon */ switch ( command2 ) { case 'd': /* add */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (attrs = get_modlist( NULL, "attr? ", "value? " )) == NULL ) break; if ( (id = ldap_add( ld, dn, attrs )) == -1 ) ldap_perror( ld, "ldap_add" ); else printf( "Add initiated with id %d\n", id ); break; case 'b': /* abandon */ getline( line, sizeof(line), stdin, "msgid? " ); id = atoi( line ); if ( ldap_abandon( ld, id ) != 0 ) ldap_perror( ld, "ldap_abandon" ); else printf( "Abandon successful\n" ); break; default: printf( "Possibilities: [ad]d, [ab]ort\n" ); } break; case 'b': /* asynch bind */ #ifdef KERBEROS getline( line, sizeof(line), stdin, "method (0->simple, 1->krbv41, 2->krbv42)? " ); method = atoi( line ) | 0x80; #else /* KERBEROS */ method = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) getline( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind( ld, dn, passwd, method ) == -1 ) { fprintf( stderr, "ldap_bind failed\n" ); ldap_perror( ld, "ldap_bind" ); } else { printf( "Bind initiated\n" ); bound = 1; } break; case 'B': /* synch bind */ #ifdef KERBEROS getline( line, sizeof(line), stdin, "method 0->simple 1->krbv41 2->krbv42 3->krb? " ); method = atoi( line ); if ( method == 3 ) method = LDAP_AUTH_KRBV4; else method = method | 0x80; #else /* KERBEROS */ method = LDAP_AUTH_SIMPLE; #endif /* KERBEROS */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( dn[0] != '\0' ) getline( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind_s( ld, dn, passwd, method ) != LDAP_SUCCESS ) { fprintf( stderr, "ldap_bind_s failed\n" ); ldap_perror( ld, "ldap_bind_s" ); } else { printf( "Bind successful\n" ); bound = 1; } break; case 'c': /* compare */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); getline( attr, sizeof(attr), stdin, "attr? " ); getline( value, sizeof(value), stdin, "value? " ); if ( (id = ldap_compare( ld, dn, attr, value )) == -1 ) ldap_perror( ld, "ldap_compare" ); else printf( "Compare initiated with id %d\n", id ); break; case 'd': /* turn on debugging */ #ifdef LDAP_DEBUG getline( line, sizeof(line), stdin, "debug level? " ); ldap_debug = atoi( line ); if ( ldap_debug & LDAP_DEBUG_PACKETS ) { lber_debug = ldap_debug; } #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'E': /* explode a dn */ getline( line, sizeof(line), stdin, "dn? " ); exdn = ldap_explode_dn( line, 0 ); for ( i = 0; exdn != NULL && exdn[i] != NULL; i++ ) { printf( "\t%s\n", exdn[i] ); } break; case 'g': /* set next msgid */ getline( line, sizeof(line), stdin, "msgid? " ); ld->ld_msgid = atoi( line ); break; case 'v': /* set version number */ getline( line, sizeof(line), stdin, "version? " ); ld->ld_version = atoi( line ); break; case 'm': /* modify or modifyrdn */ if ( strncmp( line, "modify", 4 ) == 0 ) { getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (mods = get_modlist( "mod (0=>add, 1=>delete, 2=>replace -1=>done)? ", "attribute type? ", "attribute value? " )) == NULL ) break; if ( (id = ldap_modify( ld, dn, mods )) == -1 ) ldap_perror( ld, "ldap_modify" ); else printf( "Modify initiated with id %d\n", id ); } else if ( strncmp( line, "modrdn", 4 ) == 0 ) { getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); getline( rdn, sizeof(rdn), stdin, "newrdn? " ); if ( (id = ldap_modrdn( ld, dn, rdn )) == -1 ) ldap_perror( ld, "ldap_modrdn" ); else printf( "Modrdn initiated with id %d\n", id ); } else { printf( "Possibilities: [modi]fy, [modr]dn\n" ); } break; case 'q': /* quit */ #ifdef CLDAP if ( cldapflg ) cldap_close( ld ); #endif /* CLDAP */ #ifdef LDAP_REFERRALS if ( !cldapflg ) #else /* LDAP_REFERRALS */ if ( !cldapflg && bound ) #endif /* LDAP_REFERRALS */ ldap_unbind( ld ); exit( 0 ); break; case 'r': /* result or remove */ switch ( command3 ) { case 's': /* result */ getline( line, sizeof(line), stdin, "msgid (-1=>any)? " ); if ( line[0] == '\0' ) id = -1; else id = atoi( line ); getline( line, sizeof(line), stdin, "all (0=>any, 1=>all)? " ); if ( line[0] == '\0' ) all = 1; else all = atoi( line ); if (( msgtype = ldap_result( ld, id, all, &timeout, &res )) < 1 ) { ldap_perror( ld, "ldap_result" ); break; } printf( "\nresult: msgtype %d msgid %d\n", msgtype, res->lm_msgid ); handle_result( ld, res ); res = NULLMSG; break; case 'm': /* remove */ getline( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (id = ldap_delete( ld, dn )) == -1 ) ldap_perror( ld, "ldap_delete" ); else printf( "Remove initiated with id %d\n", id ); break; default: printf( "Possibilities: [rem]ove, [res]ult\n" ); break; } break; case 's': /* search */ getline( dn, sizeof(dn), stdin, "searchbase? " ); strcat( dn, dnsuffix ); getline( line, sizeof(line), stdin, "scope (0=Base, 1=One Level, 2=Subtree)? " ); scope = atoi( line ); getline( filter, sizeof(filter), stdin, "search filter (e.g. sn=jones)? " ); types = get_list( "attrs to return? " ); getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if ( cldapflg ) { #ifdef CLDAP getline( line, sizeof(line), stdin, "Requestor DN (for logging)? " ); if ( cldap_search_s( ld, dn, scope, filter, types, attrsonly, &res, line ) != 0 ) { ldap_perror( ld, "cldap_search_s" ); } else { printf( "\nresult: msgid %d\n", res->lm_msgid ); handle_result( ld, res ); res = NULLMSG; } #endif /* CLDAP */ } else { if (( id = ldap_search( ld, dn, scope, filter, types, attrsonly )) == -1 ) { ldap_perror( ld, "ldap_search" ); } else { printf( "Search initiated with id %d\n", id ); } } free_list( types ); break; case 't': /* set timeout value */ getline( line, sizeof(line), stdin, "timeout? " ); timeout.tv_sec = atoi( line ); break; case 'U': /* set ufn search prefix */ getline( line, sizeof(line), stdin, "ufn prefix? " ); ldap_ufn_setprefix( ld, line ); break; case 'u': /* user friendly search w/optional timeout */ getline( dn, sizeof(dn), stdin, "ufn? " ); strcat( dn, dnsuffix ); types = get_list( "attrs to return? " ); getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if ( command2 == 't' ) { id = ldap_ufn_search_c( ld, dn, types, attrsonly, &res, ldap_ufn_timeout, &timeout ); } else { id = ldap_ufn_search_s( ld, dn, types, attrsonly, &res ); } if ( res == NULL ) ldap_perror( ld, "ldap_ufn_search" ); else { printf( "\nresult: err %d\n", id ); handle_result( ld, res ); res = NULLMSG; } free_list( types ); break; case 'l': /* URL search */ getline( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); getline( line, sizeof(line), stdin, "LDAP URL? " ); if (( id = ldap_url_search( ld, line, attrsonly )) == -1 ) { ldap_perror( ld, "ldap_url_search" ); } else { printf( "URL search initiated with id %d\n", id ); } break; case 'p': /* parse LDAP URL */ getline( line, sizeof(line), stdin, "LDAP URL? " ); if (( i = ldap_url_parse( line, &ludp )) != 0 ) { fprintf( stderr, "ldap_url_parse: error %d\n", i ); } else { printf( "\t host: " ); if ( ludp->lud_host == NULL ) { printf( "DEFAULT\n" ); } else { printf( "<%s>\n", ludp->lud_host ); } printf( "\t port: " ); if ( ludp->lud_port == 0 ) { printf( "DEFAULT\n" ); } else { printf( "%d\n", ludp->lud_port ); } printf( "\t dn: <%s>\n", ludp->lud_dn ); printf( "\t attrs:" ); if ( ludp->lud_attrs == NULL ) { printf( " ALL" ); } else { for ( i = 0; ludp->lud_attrs[ i ] != NULL; ++i ) { printf( " <%s>", ludp->lud_attrs[ i ] ); } } printf( "\n\t scope: %s\n", ludp->lud_scope == LDAP_SCOPE_ONELEVEL ? "ONE" : ludp->lud_scope == LDAP_SCOPE_BASE ? "BASE" : ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "SUB" : "**invalid**" ); printf( "\tfilter: <%s>\n", ludp->lud_filter ); ldap_free_urldesc( ludp ); } break; case 'n': /* set dn suffix, for convenience */ getline( line, sizeof(line), stdin, "DN suffix? " ); strcpy( dnsuffix, line ); break; case 'e': /* enable cache */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "Cache timeout (secs)? " ); i = atoi( line ); getline( line, sizeof(line), stdin, "Maximum memory to use (bytes)? " ); if ( ldap_enable_cache( ld, i, atoi( line )) == 0 ) { printf( "local cache is on\n" ); } else { printf( "ldap_enable_cache failed\n" ); } #endif /* NO_CACHE */ break; case 'x': /* uncache entry */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "DN? " ); ldap_uncache_entry( ld, line ); #endif /* NO_CACHE */ break; case 'X': /* uncache request */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "request msgid? " ); ldap_uncache_request( ld, atoi( line )); #endif /* NO_CACHE */ break; case 'o': /* set ldap options */ getline( line, sizeof(line), stdin, "alias deref (0=never, 1=searching, 2" "=finding, 3=always)?" ); ld->ld_deref = atoi( line ); getline( line, sizeof(line), stdin, "timelimit?" ); ld->ld_timelimit = atoi( line ); getline( line, sizeof(line), stdin, "sizelimit?" ); ld->ld_sizelimit = atoi( line ); ld->ld_options = 0; #ifdef STR_TRANSLATION getline( line, sizeof(line), stdin, "Automatic translation of T.61 strings " "(0=no, 1=yes)?" ); if ( atoi( line ) == 0 ) { ld->ld_lberoptions &= ~LBER_TRANSLATE_STRINGS; } else { ld->ld_lberoptions |= LBER_TRANSLATE_STRINGS; #ifdef LDAP_CHARSET_8859 getline( line, sizeof(line), stdin, "Translate to/from ISO-8859 " "(0=no, 1=yes?" ); if ( atoi( line ) != 0 ) { ldap_set_string_translators( ld, ldap_8859_to_t61, ldap_t61_to_8859 ); } #endif /* LDAP_CHARSET_8859 */ } #endif /* STR_TRANSLATION */ #ifdef LDAP_DNS getline( line, sizeof(line), stdin, "Use DN & DNS to determine where to send " "requests (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { ld->ld_options |= LDAP_OPT_DNS; } #endif /* LDAP_DNS */ #ifdef LDAP_REFERRALS getline( line, sizeof(line), stdin, "Recognize and chase referrals (0=no, 1=yes)?"); if ( atoi( line ) != 0 ) { ld->ld_options |= LDAP_OPT_REFERRALS; getline( line, sizeof(line), stdin, "Prompt for bind credentials when " "chasing referrals (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { ldap_set_rebind_proc( ld, bind_prompt ); } } #endif /* LDAP_REFERRALS */ break; case 'O': /* set cache options */ #ifdef NO_CACHE printf( NOCACHEERRMSG ); #else /* NO_CACHE */ getline( line, sizeof(line), stdin, "cache errors (0=smart, 1=never, 2=always)?" ); switch( atoi( line )) { case 0: ldap_set_cache_options( ld, 0 ); break; case 1: ldap_set_cache_options( ld, LDAP_CACHE_OPT_CACHENOERRS ); break; case 2: ldap_set_cache_options( ld, LDAP_CACHE_OPT_CACHEALLERRS ); break; default: printf( "not a valid cache option\n" ); } #endif /* NO_CACHE */ break; case '?': /* help */ printf( "Commands: [ad]d [ab]andon [b]ind\n" ); printf( " [B]ind async [c]ompare [l]URL search\n" ); printf( " [modi]fy [modr]dn [rem]ove\n" ); printf( " [res]ult [s]earch [q]uit/unbind\n\n" ); printf( " [u]fn search [ut]fn search with timeout\n" ); printf( " [d]ebug [e]nable cache set ms[g]id\n" ); printf( " d[n]suffix [t]imeout [v]ersion\n" ); printf( " [U]fn prefix [x]uncache entry [X]uncache request\n" ); printf( " [?]help [o]ptions [O]cache options\n" ); printf( " [E]xplode dn [p]arse LDAP URL\n" ); break; default: printf( "Invalid command. Type ? for help.\n" ); break; } (void) memset( line, '\0', sizeof(line) ); } return( 0 ); }
static isc_result_t ldapdb_search(const char *zone, const char *name, void *dbdata, void *retdata, void *methods, void *clientinfo) #endif /* DNS_CLIENTINFO_VERSION */ { struct ldapdb_data *data = dbdata; isc_result_t result = ISC_R_NOTFOUND; LDAP **ldp; LDAPMessage *res, *e; char *fltr, *a, **vals = NULL, **names = NULL; char type[64]; #ifdef LDAPDB_RFC1823API void *ptr; #else BerElement *ptr; #endif int i, j, errno, msgid; UNUSED(methods); UNUSED(clientinfo); ldp = ldapdb_getconn(data); if (ldp == NULL) return (ISC_R_FAILURE); if (*ldp == NULL) { ldapdb_bind(data, ldp); if (*ldp == NULL) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': bind failed", zone); return (ISC_R_FAILURE); } } if (name == NULL) { fltr = data->filterall; } else { if (strlen(name) > MAXNAMELEN) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': name %s too long", zone, name); return (ISC_R_FAILURE); } sprintf(data->filtername, "%s))", name); fltr = data->filterone; } msgid = ldap_search(*ldp, data->base, LDAP_SCOPE_SUBTREE, fltr, NULL, 0); if (msgid == -1) { ldapdb_bind(data, ldp); if (*ldp != NULL) msgid = ldap_search(*ldp, data->base, LDAP_SCOPE_SUBTREE, fltr, NULL, 0); } if (*ldp == NULL || msgid == -1) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': search failed, filter %s", zone, fltr); return (ISC_R_FAILURE); } /* Get the records one by one as they arrive and return them to bind */ while ((errno = ldap_result(*ldp, msgid, 0, NULL, &res)) != LDAP_RES_SEARCH_RESULT ) { LDAP *ld = *ldp; int ttl = data->defaultttl; /* not supporting continuation references at present */ if (errno != LDAP_RES_SEARCH_ENTRY) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': ldap_result returned %d", zone, errno); ldap_msgfree(res); return (ISC_R_FAILURE); } /* only one entry per result message */ e = ldap_first_entry(ld, res); if (e == NULL) { ldap_msgfree(res); isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': ldap_first_entry failed", zone); return (ISC_R_FAILURE); } if (name == NULL) { names = ldap_get_values(ld, e, "relativeDomainName"); if (names == NULL) continue; } vals = ldap_get_values(ld, e, "dNSTTL"); if (vals != NULL) { ttl = atoi(vals[0]); ldap_value_free(vals); } for (a = ldap_first_attribute(ld, e, &ptr); a != NULL; a = ldap_next_attribute(ld, e, ptr)) { char *s; for (s = a; *s; s++) *s = toupper(*s); s = strstr(a, "RECORD"); if ((s == NULL) || (s == a) || (s - a >= (signed int)sizeof(type))) { #ifndef LDAPDB_RFC1823API ldap_memfree(a); #endif continue; } strncpy(type, a, s - a); type[s - a] = '\0'; vals = ldap_get_values(ld, e, a); if (vals != NULL) { for (i = 0; vals[i] != NULL; i++) { if (name != NULL) { result = dns_sdb_putrr(retdata, type, ttl, vals[i]); } else { for (j = 0; names[j] != NULL; j++) { result = dns_sdb_putnamedrr(retdata, names[j], type, ttl, vals[i]); if (result != ISC_R_SUCCESS) break; } } ; if (result != ISC_R_SUCCESS) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': dns_sdb_put... failed for %s", zone, vals[i]); ldap_value_free(vals); #ifndef LDAPDB_RFC1823API ldap_memfree(a); if (ptr != NULL) ber_free(ptr, 0); #endif if (name == NULL) ldap_value_free(names); ldap_msgfree(res); return (ISC_R_FAILURE); } } ldap_value_free(vals); } #ifndef LDAPDB_RFC1823API ldap_memfree(a); #endif } #ifndef LDAPDB_RFC1823API if (ptr != NULL) ber_free(ptr, 0); #endif if (name == NULL) ldap_value_free(names); /* free this result */ ldap_msgfree(res); } /* free final result */ ldap_msgfree(res); return (result); }
int main( int argc, char **argv ) { LDAP *ld = NULL; int i, c, port, errflg, method, id, msgtype; char line[256], command1, command2, command3; char passwd[64], dn[256], rdn[64], attr[64], value[256]; char filter[256], *host, **types; char **exdn; static const char usage[] = "usage: %s [-u] [-h host] [-d level] [-s dnsuffix] [-p port] [-t file] [-T file]\n"; int bound, all, scope, attrsonly; LDAPMessage *res; LDAPMod **mods, **attrs; struct timeval timeout; char *copyfname = NULL; int copyoptions = 0; LDAPURLDesc *ludp; host = NULL; port = LDAP_PORT; dnsuffix = ""; errflg = 0; while (( c = getopt( argc, argv, "h:d:s:p:t:T:" )) != -1 ) { switch( c ) { case 'd': #ifdef LDAP_DEBUG ldap_debug = atoi( optarg ); #ifdef LBER_DEBUG if ( ldap_debug & LDAP_DEBUG_PACKETS ) { ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug ); } #endif #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'h': host = optarg; break; case 's': dnsuffix = optarg; break; case 'p': port = atoi( optarg ); break; case 't': /* copy ber's to given file */ copyfname = strdup( optarg ); /* copyoptions = LBER_TO_FILE; */ break; case 'T': /* only output ber's to given file */ copyfname = strdup( optarg ); /* copyoptions = (LBER_TO_FILE | LBER_TO_FILE_ONLY); */ break; default: ++errflg; } } if ( host == NULL && optind == argc - 1 ) { host = argv[ optind ]; ++optind; } if ( errflg || optind < argc - 1 ) { fprintf( stderr, usage, argv[ 0 ] ); exit( EXIT_FAILURE ); } printf( "ldap_init( %s, %d )\n", host == NULL ? "(null)" : host, port ); ld = ldap_init( host, port ); if ( ld == NULL ) { perror( "ldap_init" ); exit( EXIT_FAILURE ); } if ( copyfname != NULL ) { if ( ( ld->ld_sb->sb_fd = open( copyfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) { perror( copyfname ); exit ( EXIT_FAILURE ); } ld->ld_sb->sb_options = copyoptions; } bound = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; (void) memset( line, '\0', sizeof(line) ); while ( get_line( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) { command1 = line[0]; command2 = line[1]; command3 = line[2]; switch ( command1 ) { case 'a': /* add or abandon */ switch ( command2 ) { case 'd': /* add */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (attrs = get_modlist( NULL, "attr? ", "value? " )) == NULL ) break; if ( (id = ldap_add( ld, dn, attrs )) == -1 ) ldap_perror( ld, "ldap_add" ); else printf( "Add initiated with id %d\n", id ); break; case 'b': /* abandon */ get_line( line, sizeof(line), stdin, "msgid? " ); id = atoi( line ); if ( ldap_abandon( ld, id ) != 0 ) ldap_perror( ld, "ldap_abandon" ); else printf( "Abandon successful\n" ); break; default: printf( "Possibilities: [ad]d, [ab]ort\n" ); } break; case 'b': /* asynch bind */ method = LDAP_AUTH_SIMPLE; get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) get_line( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind( ld, dn, passwd, method ) == -1 ) { fprintf( stderr, "ldap_bind failed\n" ); ldap_perror( ld, "ldap_bind" ); } else { printf( "Bind initiated\n" ); bound = 1; } break; case 'B': /* synch bind */ method = LDAP_AUTH_SIMPLE; get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( dn[0] != '\0' ) get_line( passwd, sizeof(passwd), stdin, "password? " ); else passwd[0] = '\0'; if ( ldap_bind_s( ld, dn, passwd, method ) != LDAP_SUCCESS ) { fprintf( stderr, "ldap_bind_s failed\n" ); ldap_perror( ld, "ldap_bind_s" ); } else { printf( "Bind successful\n" ); bound = 1; } break; case 'c': /* compare */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); get_line( attr, sizeof(attr), stdin, "attr? " ); get_line( value, sizeof(value), stdin, "value? " ); if ( (id = ldap_compare( ld, dn, attr, value )) == -1 ) ldap_perror( ld, "ldap_compare" ); else printf( "Compare initiated with id %d\n", id ); break; case 'd': /* turn on debugging */ #ifdef LDAP_DEBUG get_line( line, sizeof(line), stdin, "debug level? " ); ldap_debug = atoi( line ); #ifdef LBER_DEBUG if ( ldap_debug & LDAP_DEBUG_PACKETS ) { ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug ); } #endif #else printf( "Compile with -DLDAP_DEBUG for debugging\n" ); #endif break; case 'E': /* explode a dn */ get_line( line, sizeof(line), stdin, "dn? " ); exdn = ldap_explode_dn( line, 0 ); for ( i = 0; exdn != NULL && exdn[i] != NULL; i++ ) { printf( "\t%s\n", exdn[i] ); } break; case 'g': /* set next msgid */ get_line( line, sizeof(line), stdin, "msgid? " ); ld->ld_msgid = atoi( line ); break; case 'v': /* set version number */ get_line( line, sizeof(line), stdin, "version? " ); ld->ld_version = atoi( line ); break; case 'm': /* modify or modifyrdn */ if ( strncmp( line, "modify", 4 ) == 0 ) { get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (mods = get_modlist( "mod (0=>add, 1=>delete, 2=>replace -1=>done)? ", "attribute type? ", "attribute value? " )) == NULL ) break; if ( (id = ldap_modify( ld, dn, mods )) == -1 ) ldap_perror( ld, "ldap_modify" ); else printf( "Modify initiated with id %d\n", id ); } else if ( strncmp( line, "modrdn", 4 ) == 0 ) { get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); get_line( rdn, sizeof(rdn), stdin, "newrdn? " ); if ( (id = ldap_modrdn( ld, dn, rdn )) == -1 ) ldap_perror( ld, "ldap_modrdn" ); else printf( "Modrdn initiated with id %d\n", id ); } else { printf( "Possibilities: [modi]fy, [modr]dn\n" ); } break; case 'q': /* quit */ ldap_unbind( ld ); exit( EXIT_SUCCESS ); break; case 'r': /* result or remove */ switch ( command3 ) { case 's': /* result */ get_line( line, sizeof(line), stdin, "msgid (-1=>any)? " ); if ( line[0] == '\0' ) id = -1; else id = atoi( line ); get_line( line, sizeof(line), stdin, "all (0=>any, 1=>all)? " ); if ( line[0] == '\0' ) all = 1; else all = atoi( line ); if (( msgtype = ldap_result( ld, id, all, &timeout, &res )) < 1 ) { ldap_perror( ld, "ldap_result" ); break; } printf( "\nresult: msgtype %d msgid %d\n", msgtype, res->lm_msgid ); handle_result( ld, res ); res = NULL; break; case 'm': /* remove */ get_line( dn, sizeof(dn), stdin, "dn? " ); strcat( dn, dnsuffix ); if ( (id = ldap_delete( ld, dn )) == -1 ) ldap_perror( ld, "ldap_delete" ); else printf( "Remove initiated with id %d\n", id ); break; default: printf( "Possibilities: [rem]ove, [res]ult\n" ); break; } break; case 's': /* search */ get_line( dn, sizeof(dn), stdin, "searchbase? " ); strcat( dn, dnsuffix ); get_line( line, sizeof(line), stdin, "scope (0=baseObject, 1=oneLevel, 2=subtree, 3=children)? " ); scope = atoi( line ); get_line( filter, sizeof(filter), stdin, "search filter (e.g. sn=jones)? " ); types = get_list( "attrs to return? " ); get_line( line, sizeof(line), stdin, "attrsonly (0=attrs&values, 1=attrs only)? " ); attrsonly = atoi( line ); if (( id = ldap_search( ld, dn, scope, filter, types, attrsonly )) == -1 ) { ldap_perror( ld, "ldap_search" ); } else { printf( "Search initiated with id %d\n", id ); } free_list( types ); break; case 't': /* set timeout value */ get_line( line, sizeof(line), stdin, "timeout? " ); timeout.tv_sec = atoi( line ); break; case 'p': /* parse LDAP URL */ get_line( line, sizeof(line), stdin, "LDAP URL? " ); if (( i = ldap_url_parse( line, &ludp )) != 0 ) { fprintf( stderr, "ldap_url_parse: error %d\n", i ); } else { printf( "\t host: " ); if ( ludp->lud_host == NULL ) { printf( "DEFAULT\n" ); } else { printf( "<%s>\n", ludp->lud_host ); } printf( "\t port: " ); if ( ludp->lud_port == 0 ) { printf( "DEFAULT\n" ); } else { printf( "%d\n", ludp->lud_port ); } printf( "\t dn: <%s>\n", ludp->lud_dn ); printf( "\t attrs:" ); if ( ludp->lud_attrs == NULL ) { printf( " ALL" ); } else { for ( i = 0; ludp->lud_attrs[ i ] != NULL; ++i ) { printf( " <%s>", ludp->lud_attrs[ i ] ); } } printf( "\n\t scope: %s\n", ludp->lud_scope == LDAP_SCOPE_BASE ? "baseObject" : ludp->lud_scope == LDAP_SCOPE_ONELEVEL ? "oneLevel" : ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "subtree" #ifdef LDAP_SCOPE_SUBORDINATE : ludp->lud_scope == LDAP_SCOPE_SUBORDINATE ? "children" #endif : "**invalid**" ); printf( "\tfilter: <%s>\n", ludp->lud_filter ); ldap_free_urldesc( ludp ); } break; case 'n': /* set dn suffix, for convenience */ get_line( line, sizeof(line), stdin, "DN suffix? " ); strcpy( dnsuffix, line ); break; case 'o': /* set ldap options */ get_line( line, sizeof(line), stdin, "alias deref (0=never, 1=searching, 2=finding, 3=always)?" ); ld->ld_deref = atoi( line ); get_line( line, sizeof(line), stdin, "timelimit?" ); ld->ld_timelimit = atoi( line ); get_line( line, sizeof(line), stdin, "sizelimit?" ); ld->ld_sizelimit = atoi( line ); LDAP_BOOL_ZERO(&ld->ld_options); get_line( line, sizeof(line), stdin, "Recognize and chase referrals (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { LDAP_BOOL_SET(&ld->ld_options, LDAP_BOOL_REFERRALS); get_line( line, sizeof(line), stdin, "Prompt for bind credentials when chasing referrals (0=no, 1=yes)?" ); if ( atoi( line ) != 0 ) { ldap_set_rebind_proc( ld, bind_prompt, NULL ); } } break; case '?': /* help */ printf( "Commands: [ad]d [ab]andon [b]ind\n" " [B]ind async [c]ompare\n" " [modi]fy [modr]dn [rem]ove\n" " [res]ult [s]earch [q]uit/unbind\n\n" " [d]ebug set ms[g]id\n" " d[n]suffix [t]imeout [v]ersion\n" " [?]help [o]ptions" " [E]xplode dn [p]arse LDAP URL\n" ); break; default: printf( "Invalid command. Type ? for help.\n" ); break; } (void) memset( line, '\0', sizeof(line) ); } return( 0 ); }
/* * Do an LDAP lookup to the server described in the info argument. * * Args info -- LDAP info for server. * string -- String to lookup. * cust -- Possible custom filter description. * wp_err -- We set this is we get a white pages error. * name_in_error -- Caller sets this if they want us to include the server * name in error messages. * * Returns Results of lookup, NULL if lookup failed. */ LDAP_SERV_RES_S * ldap_lookup(LDAP_SERV_S *info, char *string, CUSTOM_FILT_S *cust, WP_ERR_S *wp_err, int name_in_error) { char ebuf[900]; char buf[900]; char *serv, *base, *serv_errstr; char *mailattr, *snattr, *gnattr, *cnattr; int we_cancel = 0, we_turned_on = 0; LDAP_SERV_RES_S *serv_res = NULL; LDAP *ld; long pwdtrial = 0L; int ld_errnum; char *ld_errstr; if(!info) return(serv_res); serv = cpystr((info->serv && *info->serv) ? info->serv : "?"); if(name_in_error) snprintf(ebuf, sizeof(ebuf), " (%s)", (info->nick && *info->nick) ? info->nick : serv); else ebuf[0] = '\0'; serv_errstr = cpystr(ebuf); base = cpystr(info->base ? info->base : ""); if(info->port < 0) info->port = LDAP_PORT; if(info->type < 0) info->type = DEF_LDAP_TYPE; if(info->srch < 0) info->srch = DEF_LDAP_SRCH; if(info->time < 0) info->time = DEF_LDAP_TIME; if(info->size < 0) info->size = DEF_LDAP_SIZE; if(info->scope < 0) info->scope = DEF_LDAP_SCOPE; mailattr = (info->mailattr && info->mailattr[0]) ? info->mailattr : DEF_LDAP_MAILATTR; snattr = (info->snattr && info->snattr[0]) ? info->snattr : DEF_LDAP_SNATTR; gnattr = (info->gnattr && info->gnattr[0]) ? info->gnattr : DEF_LDAP_GNATTR; cnattr = (info->cnattr && info->cnattr[0]) ? info->cnattr : DEF_LDAP_CNATTR; /* * We may want to keep ldap handles open, but at least for * now, re-open them every time. */ dprint((3, "ldap_lookup(%s,%d)\n", serv ? serv : "?", info->port)); snprintf(ebuf, sizeof(ebuf), "Searching%s%s%s on %s", (string && *string) ? " for \"" : "", (string && *string) ? string : "", (string && *string) ? "\"" : "", serv); we_turned_on = intr_handling_on(); /* this erases keymenu */ we_cancel = busy_cue(ebuf, NULL, 0); if(wp_err->mangled) *(wp_err->mangled) = 1; #ifdef _SOLARIS_SDK if(info->tls || info->tlsmust) ldapssl_client_init(NULL, NULL); if((ld = ldap_init(serv, info->port)) == NULL) #else #if (LDAPAPI >= 11) if((ld = ldap_init(serv, info->port)) == NULL) #else if((ld = ldap_open(serv, info->port)) == NULL) #endif #endif { /* TRANSLATORS: All of the three args together are an error message */ snprintf(ebuf, sizeof(ebuf), _("Access to LDAP server failed: %s%s(%s)"), errno ? error_description(errno) : "", errno ? " " : "", serv); wp_err->wp_err_occurred = 1; if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } else if(!ps_global->intr_pending){ int proto = 3, tlsmustbail = 0; char pwd[NETMAXPASSWD], user[NETMAXUSER]; char *passwd = NULL; char hostbuf[1024]; NETMBX mb; #ifndef _WINDOWS int rc; #endif memset(&mb, 0, sizeof(mb)); #ifdef _SOLARIS_SDK if(info->tls || info->tlsmust) rc = ldapssl_install_routines(ld); #endif if(ldap_v3_is_supported(ld) && our_ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &proto) == 0){ dprint((5, "ldap: using version 3 protocol\n")); } /* * If we don't set RESTART then the select() waiting for the answer * in libldap will be interrupted and stopped by our busy_cue. */ our_ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON); /* * If we need to authenticate, get the password. We are not * supporting SASL authentication, just LDAP simple. */ if(info->binddn && info->binddn[0]){ char pmt[500]; char *space; snprintf(hostbuf, sizeof(hostbuf), "{%s}dummy", info->serv ? info->serv : "?"); /* * We don't handle multiple space-delimited hosts well. * We don't know which we're asking for a password for. * We're not connected yet so we can't know. */ if((space=strindex(hostbuf, ' ')) != NULL) *space = '\0'; mail_valid_net_parse_work(hostbuf, &mb, "ldap"); mb.port = info->port; mb.tlsflag = (info->tls || info->tlsmust) ? 1 : 0; try_password_again: if(mb.tlsflag && (pwdtrial > 0 || #ifndef _WINDOWS #ifdef _SOLARIS_SDK (rc == LDAP_SUCCESS) #else /* !_SOLARIS_SDK */ ((rc=ldap_start_tls_s(ld, NULL, NULL)) == LDAP_SUCCESS) #endif /* !_SOLARIS_SDK */ #else /* _WINDOWS */ 0 /* TODO: find a way to do this in Windows */ #endif /* _WINDOWS */ )) mb.tlsflag = 1; else mb.tlsflag = 0; if((info->tls || info->tlsmust) && !mb.tlsflag){ q_status_message(SM_ORDER, 3, 5, "Not able to start TLS encryption for LDAP server"); if(info->tlsmust) tlsmustbail++; } if(!tlsmustbail){ snprintf(pmt, sizeof(pmt), " %s", (info->nick && *info->nick) ? info->nick : serv); mm_login_work(&mb, user, pwd, pwdtrial, pmt, info->binddn); if(pwd && pwd[0]) passwd = pwd; } } /* * LDAPv2 requires the bind. v3 doesn't require it but we want * to tell the server we're v3 if the server supports v3, and if the * server doesn't support v3 the bind is required. */ if(tlsmustbail || ldap_simple_bind_s(ld, info->binddn, passwd) != LDAP_SUCCESS){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); if(!tlsmustbail && info->binddn && info->binddn[0] && pwdtrial < 2L && ld_errnum == LDAP_INVALID_CREDENTIALS){ pwdtrial++; q_status_message(SM_ORDER, 3, 5, _("Invalid password")); goto try_password_again; } snprintf(ebuf, sizeof(ebuf), _("LDAP server failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); if(we_cancel) cancel_busy_cue(-1); ldap_unbind(ld); wp_err->error = cpystr(ebuf); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } else if(!ps_global->intr_pending){ int srch_res, args, slen, flen; #define TEMPLATELEN 512 char filt_template[TEMPLATELEN + 1]; char filt_format[2*TEMPLATELEN + 1]; char filter[2*TEMPLATELEN + 1]; char scp[2*TEMPLATELEN + 1]; char *p, *q; LDAPMessage *res = NULL; int intr_happened = 0; int tl; tl = (info->time == 0) ? info->time : info->time + 10; our_ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &tl); our_ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &info->size); /* * If a custom filter has been passed in and it doesn't include a * request to combine it with the configured filter, then replace * any configured filter with the passed in filter. */ if(cust && cust->filt && !cust->combine){ if(info->cust) fs_give((void **)&info->cust); info->cust = cpystr(cust->filt); } if(info->cust && *info->cust){ /* use custom filter if present */ strncpy(filt_template, info->cust, sizeof(filt_template)); filt_template[sizeof(filt_template)-1] = '\0'; } else{ /* else use configured filter */ switch(info->type){ case LDAP_TYPE_SUR: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", snattr); break; case LDAP_TYPE_GIVEN: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", gnattr); break; case LDAP_TYPE_EMAIL: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", mailattr); break; case LDAP_TYPE_CN_EMAIL: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))", cnattr, mailattr); break; case LDAP_TYPE_SUR_GIVEN: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))", snattr, gnattr); break; case LDAP_TYPE_SEVERAL: snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s)(%s=%%s)(%s=%%s))", cnattr, mailattr, snattr, gnattr); break; default: case LDAP_TYPE_CN: snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", cnattr); break; } } /* just copy if custom */ if(info->cust && *info->cust) info->srch = LDAP_SRCH_EQUALS; p = filt_template; q = filt_format; memset((void *)filt_format, 0, sizeof(filt_format)); args = 0; while(*p && (q - filt_format) + 4 < sizeof(filt_format)){ if(*p == '%' && *(p+1) == 's'){ args++; switch(info->srch){ /* Exact match */ case LDAP_SRCH_EQUALS: *q++ = *p++; *q++ = *p++; break; /* Append wildcard after %s */ case LDAP_SRCH_BEGINS: *q++ = *p++; *q++ = *p++; *q++ = '*'; break; /* Insert wildcard before %s */ case LDAP_SRCH_ENDS: *q++ = '*'; *q++ = *p++; *q++ = *p++; break; /* Put wildcard before and after %s */ default: case LDAP_SRCH_CONTAINS: *q++ = '*'; *q++ = *p++; *q++ = *p++; *q++ = '*'; break; } } else *q++ = *p++; } if(q - filt_format < sizeof(filt_format)) *q = '\0'; filt_format[sizeof(filt_format)-1] = '\0'; /* * If combine is lit we put the custom filter and the filt_format * filter and combine them with an &. */ if(cust && cust->filt && cust->combine){ char *combined; size_t l; l = strlen(filt_format) + strlen(cust->filt) + 3; combined = (char *) fs_get((l+1) * sizeof(char)); snprintf(combined, l+1, "(&%s%s)", cust->filt, filt_format); strncpy(filt_format, combined, sizeof(filt_format)); filt_format[sizeof(filt_format)-1] = '\0'; fs_give((void **) &combined); } /* * Ad hoc attempt to make "Steve Hubert" match * Steven Hubert but not Steven Shubert. * We replace a <SPACE> with * <SPACE> (not * <SPACE> *). */ memset((void *)scp, 0, sizeof(scp)); if(info->nosub) strncpy(scp, string, sizeof(scp)); else{ p = string; q = scp; while(*p && (q - scp) + 1 < sizeof(scp)){ if(*p == SPACE && *(p+1) != SPACE){ *q++ = '*'; *q++ = *p++; } else *q++ = *p++; } } scp[sizeof(scp)-1] = '\0'; slen = strlen(scp); flen = strlen(filt_format); /* truncate string if it will overflow filter */ if(args*slen + flen - 2*args > sizeof(filter)-1) scp[(sizeof(filter)-1 - flen)/args] = '\0'; /* * Replace %s's with scp. */ switch(args){ case 0: snprintf(filter, sizeof(filter), "%s", filt_format); break; case 1: snprintf(filter, sizeof(filter), filt_format, scp); break; case 2: snprintf(filter, sizeof(filter), filt_format, scp, scp); break; case 3: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp); break; case 4: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp); break; case 5: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp); break; case 6: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp); break; case 7: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp); break; case 8: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp); break; case 9: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp, scp); break; case 10: default: snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp, scp, scp, scp); break; } /* replace double *'s with single *'s in filter */ for(p = q = filter; *p; p++) if(*p != '*' || p == filter || *(p-1) != '*') *q++ = *p; *q = '\0'; (void) removing_double_quotes(base); dprint((5, "about to ldap_search(\"%s\", %s)\n", base ? base : "?", filter ? filter : "?")); if(ps_global->intr_pending) srch_res = LDAP_PROTOCOL_ERROR; else{ int msgid; time_t start_time; start_time = time((time_t *)0); dprint((6, "ldap_lookup: calling ldap_search\n")); msgid = ldap_search(ld, base, info->scope, filter, NULL, 0); if(msgid == -1) srch_res = our_ldap_get_lderrno(ld, NULL, NULL); else{ int lres; /* * Warning: struct timeval is not portable. However, since it is * part of LDAP api it must be portable to all platforms LDAP * has been ported to. */ struct timeval t; t.tv_sec = 1; t.tv_usec = 0; do { if(ps_global->intr_pending) intr_happened = 1; dprint((6, "ldap_result(id=%d): ", msgid)); if((lres=ldap_result(ld, msgid, LDAP_MSG_ALL, &t, &res)) == -1){ /* error */ srch_res = our_ldap_get_lderrno(ld, NULL, NULL); dprint((6, "error (-1 returned): ld_errno=%d\n", srch_res)); } else if(lres == 0){ /* timeout, no results available */ if(intr_happened){ ldap_abandon(ld, msgid); srch_res = LDAP_PROTOCOL_ERROR; if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS) our_ldap_set_lderrno(ld, LDAP_PROTOCOL_ERROR, NULL, NULL); dprint((6, "timeout, intr: srch_res=%d\n", srch_res)); } else if(info->time > 0 && ((long)time((time_t *)0) - start_time) > info->time){ /* try for partial results */ t.tv_sec = 0; t.tv_usec = 0; lres = ldap_result(ld, msgid, LDAP_MSG_RECEIVED, &t, &res); if(lres > 0 && lres != LDAP_RES_SEARCH_RESULT){ srch_res = LDAP_SUCCESS; dprint((6, "partial result: lres=0x%x\n", lres)); } else{ if(lres == 0) ldap_abandon(ld, msgid); srch_res = LDAP_TIMEOUT; if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS) our_ldap_set_lderrno(ld, LDAP_TIMEOUT, NULL, NULL); dprint((6, "timeout, total_time (%d), srch_res=%d\n", info->time, srch_res)); } } else{ dprint((6, "timeout\n")); } } else{ srch_res = ldap_result2error(ld, res, 0); dprint((6, "lres=0x%x, srch_res=%d\n", lres, srch_res)); } }while(lres == 0 && !(intr_happened || (info->time > 0 && ((long)time((time_t *)0) - start_time) > info->time))); } } if(intr_happened){ wp_exit = 1; if(we_cancel) cancel_busy_cue(-1); if(wp_err->error) fs_give((void **)&wp_err->error); else{ q_status_message(SM_ORDER, 0, 1, "Interrupt"); display_message('x'); fflush(stdout); } if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } else if(srch_res != LDAP_SUCCESS && srch_res != LDAP_TIMELIMIT_EXCEEDED && srch_res != LDAP_RESULTS_TOO_LARGE && srch_res != LDAP_TIMEOUT && srch_res != LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } else{ int cnt; cnt = ldap_count_entries(ld, res); if(cnt > 0){ if(srch_res == LDAP_TIMELIMIT_EXCEEDED || srch_res == LDAP_RESULTS_TOO_LARGE || srch_res == LDAP_TIMEOUT || srch_res == LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP partial results: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); dprint((2, "%s\n", ebuf)); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); } dprint((5, "Matched %d entries on %s\n", cnt, serv ? serv : "?")); serv_res = (LDAP_SERV_RES_S *)fs_get(sizeof(LDAP_SERV_RES_S)); memset((void *)serv_res, 0, sizeof(*serv_res)); serv_res->ld = ld; serv_res->res = res; serv_res->info_used = copy_ldap_serv_info(info); /* Save by reference? */ if(info->ref){ snprintf(buf, sizeof(buf), "%s:%s", serv, comatose(info->port)); serv_res->serv = cpystr(buf); } else serv_res->serv = NULL; serv_res->next = NULL; } else{ if(srch_res == LDAP_TIMELIMIT_EXCEEDED || srch_res == LDAP_RESULTS_TOO_LARGE || srch_res == LDAP_TIMEOUT || srch_res == LDAP_SIZELIMIT_EXCEEDED){ wp_err->wp_err_occurred = 1; wp_err->ldap_errno = srch_res; ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr); snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"), ldap_err2string(ld_errnum), serv_errstr, (ld_errstr && *ld_errstr) ? ": " : "", (ld_errstr && *ld_errstr) ? ld_errstr : ""); if(wp_err->error) fs_give((void **)&wp_err->error); wp_err->error = cpystr(ebuf); if(we_cancel) cancel_busy_cue(-1); q_status_message(SM_ORDER, 3, 5, wp_err->error); display_message('x'); dprint((2, "%s\n", ebuf)); } dprint((5, "Matched 0 entries on %s\n", serv ? serv : "?")); if(res) ldap_msgfree(res); if(ld) ldap_unbind(ld); res = NULL; ld = NULL; } } } } if(we_cancel) cancel_busy_cue(-1); if(we_turned_on) intr_handling_off(); if(serv) fs_give((void **)&serv); if(base) fs_give((void **)&base); if(serv_errstr) fs_give((void **)&serv_errstr); return(serv_res); }
static int perform_ldap_search(uschar *ldap_url, uschar *server, int s_port, int search_type, uschar **res, uschar **errmsg, BOOL *defer_break, uschar *user, uschar *password, int sizelimit, int timelimit, int tcplimit, int dereference, void *referrals) { LDAPURLDesc *ludp = NULL; LDAPMessage *result = NULL; BerElement *ber; LDAP_CONNECTION *lcp; struct timeval timeout; struct timeval *timeoutptr = NULL; uschar *attr; uschar **attrp; uschar *data = NULL; uschar *dn = NULL; uschar *host; uschar **values; uschar **firstval; uschar porttext[16]; uschar *error1 = NULL; /* string representation of errcode (static) */ uschar *error2 = NULL; /* error message from the server */ uschar *matched = NULL; /* partially matched DN */ int attr_count = 0; int error_yield = DEFER; int msgid; int rc, ldap_rc, ldap_parse_rc; int port; int ptr = 0; int rescount = 0; int size = 0; BOOL attribute_found = FALSE; BOOL ldapi = FALSE; DEBUG(D_lookup) debug_printf("perform_ldap_search: ldap%s URL = \"%s\" server=%s port=%d " "sizelimit=%d timelimit=%d tcplimit=%d\n", (search_type == SEARCH_LDAP_MULTIPLE)? "m" : (search_type == SEARCH_LDAP_DN)? "dn" : (search_type == SEARCH_LDAP_AUTH)? "auth" : "", ldap_url, server, s_port, sizelimit, timelimit, tcplimit); /* Check if LDAP thinks the URL is a valid LDAP URL. We assume that if the LDAP library that is in use doesn't recognize, say, "ldapi", it will barf here. */ if (!ldap_is_ldap_url(CS ldap_url)) { *errmsg = string_sprintf("ldap_is_ldap_url: not an LDAP url \"%s\"\n", ldap_url); goto RETURN_ERROR_BREAK; } /* Parse the URL */ if ((rc = ldap_url_parse(CS ldap_url, &ludp)) != 0) { *errmsg = string_sprintf("ldap_url_parse: (error %d) parsing \"%s\"\n", rc, ldap_url); goto RETURN_ERROR_BREAK; } /* If the host name is empty, take it from the separate argument, if one is given. OpenLDAP 2.0.6 sets an unset hostname to "" rather than empty, but expects NULL later in ldap_init() to mean "default", annoyingly. In OpenLDAP 2.0.11 this has changed (it uses NULL). */ if ((ludp->lud_host == NULL || ludp->lud_host[0] == 0) && server != NULL) { host = server; port = s_port; } else { host = US ludp->lud_host; if (host != NULL && host[0] == 0) host = NULL; port = ludp->lud_port; } DEBUG(D_lookup) debug_printf("after ldap_url_parse: host=%s port=%d\n", host, port); if (port == 0) port = LDAP_PORT; /* Default if none given */ sprintf(CS porttext, ":%d", port); /* For messages */ /* If the "host name" is actually a path, we are going to connect using a Unix socket, regardless of whether "ldapi" was actually specified or not. This means that a Unix socket can be declared in eldap_default_servers, and "traditional" LDAP queries using just "ldap" can be used ("ldaps" is similarly overridden). The path may start with "/" or it may already be escaped as "%2F" if it was actually declared that way in eldap_default_servers. (I did it that way the first time.) If the host name is not a path, the use of "ldapi" causes an error, except in the default case. (But lud_scheme doesn't seem to exist in older libraries.) */ if (host != NULL) { if ((host[0] == '/' || Ustrncmp(host, "%2F", 3) == 0)) { ldapi = TRUE; porttext[0] = 0; /* Remove port from messages */ } #if defined LDAP_LIB_OPENLDAP2 else if (strncmp(ludp->lud_scheme, "ldapi", 5) == 0) { *errmsg = string_sprintf("ldapi requires an absolute path (\"%s\" given)", host); goto RETURN_ERROR; } #endif } /* Count the attributes; we need this later to tell us how to format results */ for (attrp = USS ludp->lud_attrs; attrp != NULL && *attrp != NULL; attrp++) attr_count++; /* See if we can find a cached connection to this host. The port is not relevant for ldapi. The host name pointer is set to NULL if no host was given (implying the library default), rather than to the empty string. Note that in this case, there is no difference between ldap and ldapi. */ for (lcp = ldap_connections; lcp != NULL; lcp = lcp->next) { if ((host == NULL) != (lcp->host == NULL) || (host != NULL && strcmpic(lcp->host, host) != 0)) continue; if (ldapi || port == lcp->port) break; } /* Use this network timeout in any requests. */ if (tcplimit > 0) { timeout.tv_sec = tcplimit; timeout.tv_usec = 0; timeoutptr = &timeout; } /* If no cached connection found, we must open a connection to the server. If the server name is actually an absolute path, we set ldapi=TRUE above. This requests connection via a Unix socket. However, as far as I know, only OpenLDAP supports the use of sockets, and the use of ldap_initialize(). */ if (lcp == NULL) { LDAP *ld; /* --------------------------- OpenLDAP ------------------------ */ /* There seems to be a preference under OpenLDAP for ldap_initialize() instead of ldap_init(), though I have as yet been unable to find documentation that says this. (OpenLDAP documentation is sparse to non-existent). So we handle OpenLDAP differently here. Also, support for ldapi seems to be OpenLDAP-only at present. */ #ifdef LDAP_LIB_OPENLDAP2 /* We now need an empty string for the default host. Get some store in which to build a URL for ldap_initialize(). In the ldapi case, it can't be bigger than (9 + 3*Ustrlen(shost)), whereas in the other cases it can't be bigger than the host name + "ldaps:///" plus : and a port number, say 20 + the length of the host name. What we get should accommodate both, easily. */ uschar *shost = (host == NULL)? US"" : host; uschar *init_url = store_get(20 + 3 * Ustrlen(shost)); uschar *init_ptr; /* Handle connection via Unix socket ("ldapi"). We build a basic LDAP URI to contain the path name, with slashes escaped as %2F. */ if (ldapi) { int ch; init_ptr = init_url + 8; Ustrcpy(init_url, "ldapi://"); while ((ch = *shost++) != 0) { if (ch == '/') { Ustrncpy(init_ptr, "%2F", 3); init_ptr += 3; } else *init_ptr++ = ch; } *init_ptr = 0; } /* This is not an ldapi call. Just build a URI with the protocol type, host name, and port. */ else { init_ptr = Ustrchr(ldap_url, '/'); Ustrncpy(init_url, ldap_url, init_ptr - ldap_url); init_ptr = init_url + (init_ptr - ldap_url); sprintf(CS init_ptr, "//%s:%d/", shost, port); } /* Call ldap_initialize() and check the result */ DEBUG(D_lookup) debug_printf("ldap_initialize with URL %s\n", init_url); rc = ldap_initialize(&ld, CS init_url); if (rc != LDAP_SUCCESS) { *errmsg = string_sprintf("ldap_initialize: (error %d) URL \"%s\"\n", rc, init_url); goto RETURN_ERROR; } store_reset(init_url); /* Might as well save memory when we can */ /* ------------------------- Not OpenLDAP ---------------------- */ /* For libraries other than OpenLDAP, use ldap_init(). */ #else /* LDAP_LIB_OPENLDAP2 */ ld = ldap_init(CS host, port); #endif /* LDAP_LIB_OPENLDAP2 */ /* -------------------------------------------------------------- */ /* Handle failure to initialize */ if (ld == NULL) { *errmsg = string_sprintf("failed to initialize for LDAP server %s%s - %s", host, porttext, strerror(errno)); goto RETURN_ERROR; } /* Set the TCP connect time limit if available. This is something that is in Netscape SDK v4.1; I don't know about other libraries. */ #ifdef LDAP_X_OPT_CONNECT_TIMEOUT if (tcplimit > 0) { int timeout1000 = tcplimit*1000; ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, (void *)&timeout1000); } else { int notimeout = LDAP_X_IO_TIMEOUT_NO_TIMEOUT; ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, (void *)¬imeout); } #endif /* Set the TCP connect timeout. This works with OpenLDAP 2.2.14. */ #ifdef LDAP_OPT_NETWORK_TIMEOUT if (tcplimit > 0) ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, (void *)timeoutptr); #endif /* I could not get TLS to work until I set the version to 3. That version seems to be the default nowadays. The RFC is dated 1997, so I would hope that all the LDAP libraries support it. Therefore, if eldap_version hasn't been set, go for v3 if we can. */ if (eldap_version < 0) { #ifdef LDAP_VERSION3 eldap_version = LDAP_VERSION3; #else eldap_version = 2; #endif } #ifdef LDAP_OPT_PROTOCOL_VERSION ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void *)&eldap_version); #endif DEBUG(D_lookup) debug_printf("initialized for LDAP (v%d) server %s%s\n", eldap_version, host, porttext); /* If not using ldapi and TLS is available, set appropriate TLS options: hard for "ldaps" and soft otherwise. */ #ifdef LDAP_OPT_X_TLS if (!ldapi) { int tls_option; if (strncmp(ludp->lud_scheme, "ldaps", 5) == 0) { tls_option = LDAP_OPT_X_TLS_HARD; DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_HARD set\n"); } else { tls_option = LDAP_OPT_X_TLS_TRY; DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_TRY set\n"); } ldap_set_option(ld, LDAP_OPT_X_TLS, (void *)&tls_option); } #endif /* LDAP_OPT_X_TLS */ #ifdef LDAP_OPT_X_TLS_CACERTFILE if (eldap_ca_cert_file != NULL) { ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTFILE, eldap_ca_cert_file); } #endif #ifdef LDAP_OPT_X_TLS_CACERTDIR if (eldap_ca_cert_dir != NULL) { ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTDIR, eldap_ca_cert_dir); } #endif #ifdef LDAP_OPT_X_TLS_CERTFILE if (eldap_cert_file != NULL) { ldap_set_option(ld, LDAP_OPT_X_TLS_CERTFILE, eldap_cert_file); } #endif #ifdef LDAP_OPT_X_TLS_KEYFILE if (eldap_cert_key != NULL) { ldap_set_option(ld, LDAP_OPT_X_TLS_KEYFILE, eldap_cert_key); } #endif #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE if (eldap_cipher_suite != NULL) { ldap_set_option(ld, LDAP_OPT_X_TLS_CIPHER_SUITE, eldap_cipher_suite); } #endif #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT if (eldap_require_cert != NULL) { int cert_option = LDAP_OPT_X_TLS_NEVER; if (Ustrcmp(eldap_require_cert, "hard") == 0) { cert_option = LDAP_OPT_X_TLS_HARD; } else if (Ustrcmp(eldap_require_cert, "demand") == 0) { cert_option = LDAP_OPT_X_TLS_DEMAND; } else if (Ustrcmp(eldap_require_cert, "allow") == 0) { cert_option = LDAP_OPT_X_TLS_ALLOW; } else if (Ustrcmp(eldap_require_cert, "try") == 0) { cert_option = LDAP_OPT_X_TLS_TRY; } ldap_set_option(ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &cert_option); } #endif /* Now add this connection to the chain of cached connections */ lcp = store_get(sizeof(LDAP_CONNECTION)); lcp->host = (host == NULL)? NULL : string_copy(host); lcp->bound = FALSE; lcp->user = NULL; lcp->password = NULL; lcp->port = port; lcp->ld = ld; lcp->next = ldap_connections; ldap_connections = lcp; } /* Found cached connection */ else { DEBUG(D_lookup) debug_printf("re-using cached connection to LDAP server %s%s\n", host, porttext); } /* Bind with the user/password supplied, or an anonymous bind if these values are NULL, unless a cached connection is already bound with the same values. */ if (!lcp->bound || (lcp->user == NULL && user != NULL) || (lcp->user != NULL && user == NULL) || (lcp->user != NULL && user != NULL && Ustrcmp(lcp->user, user) != 0) || (lcp->password == NULL && password != NULL) || (lcp->password != NULL && password == NULL) || (lcp->password != NULL && password != NULL && Ustrcmp(lcp->password, password) != 0)) { DEBUG(D_lookup) debug_printf("%sbinding with user=%s password=%s\n", (lcp->bound)? "re-" : "", user, password); #ifdef LDAP_OPT_X_TLS /* The Oracle LDAP libraries (LDAP_LIB_TYPE=SOLARIS) don't support this: */ if (eldap_start_tls) { ldap_start_tls_s(lcp->ld, NULL, NULL); } #endif if ((msgid = ldap_bind(lcp->ld, CS user, CS password, LDAP_AUTH_SIMPLE)) == -1) { *errmsg = string_sprintf("failed to bind the LDAP connection to server " "%s%s - ldap_bind() returned -1", host, porttext); goto RETURN_ERROR; } if ((rc = ldap_result( lcp->ld, msgid, 1, timeoutptr, &result )) <= 0) { *errmsg = string_sprintf("failed to bind the LDAP connection to server " "%s%s - LDAP error: %s", host, porttext, rc == -1 ? "result retrieval failed" : "timeout" ); result = NULL; goto RETURN_ERROR; } rc = ldap_result2error( lcp->ld, result, 0 ); /* Invalid credentials when just checking credentials returns FAIL. This stops any further servers being tried. */ if (search_type == SEARCH_LDAP_AUTH && rc == LDAP_INVALID_CREDENTIALS) { DEBUG(D_lookup) debug_printf("Invalid credentials: ldapauth returns FAIL\n"); error_yield = FAIL; goto RETURN_ERROR_NOMSG; } /* Otherwise we have a problem that doesn't stop further servers from being tried. */ if (rc != LDAP_SUCCESS) { *errmsg = string_sprintf("failed to bind the LDAP connection to server " "%s%s - LDAP error %d: %s", host, porttext, rc, ldap_err2string(rc)); goto RETURN_ERROR; } /* Successful bind */ lcp->bound = TRUE; lcp->user = (user == NULL)? NULL : string_copy(user); lcp->password = (password == NULL)? NULL : string_copy(password); ldap_msgfree(result); result = NULL; } /* If we are just checking credentials, return OK. */ if (search_type == SEARCH_LDAP_AUTH) { DEBUG(D_lookup) debug_printf("Bind succeeded: ldapauth returns OK\n"); goto RETURN_OK; } /* Before doing the search, set the time and size limits (if given). Here again the different implementations of LDAP have chosen to do things differently. */ #if defined(LDAP_OPT_SIZELIMIT) ldap_set_option(lcp->ld, LDAP_OPT_SIZELIMIT, (void *)&sizelimit); ldap_set_option(lcp->ld, LDAP_OPT_TIMELIMIT, (void *)&timelimit); #else lcp->ld->ld_sizelimit = sizelimit; lcp->ld->ld_timelimit = timelimit; #endif /* Similarly for dereferencing aliases. Don't know if this is possible on an LDAP library without LDAP_OPT_DEREF. */ #if defined(LDAP_OPT_DEREF) ldap_set_option(lcp->ld, LDAP_OPT_DEREF, (void *)&dereference); #endif /* Similarly for the referral setting; should the library follow referrals that the LDAP server returns? The conditional is just in case someone uses a library without it. */ #if defined(LDAP_OPT_REFERRALS) ldap_set_option(lcp->ld, LDAP_OPT_REFERRALS, referrals); #endif /* Start the search on the server. */ DEBUG(D_lookup) debug_printf("Start search\n"); msgid = ldap_search(lcp->ld, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter, ludp->lud_attrs, 0); if (msgid == -1) { #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2 int err; ldap_get_option(lcp->ld, LDAP_OPT_ERROR_NUMBER, &err); *errmsg = string_sprintf("ldap_search failed: %d, %s", err, ldap_err2string(err)); #else *errmsg = string_sprintf("ldap_search failed"); #endif goto RETURN_ERROR; } /* Loop to pick up results as they come in, setting a timeout if one was given. */ while ((rc = ldap_result(lcp->ld, msgid, 0, timeoutptr, &result)) == LDAP_RES_SEARCH_ENTRY) { LDAPMessage *e; DEBUG(D_lookup) debug_printf("ldap_result loop\n"); for(e = ldap_first_entry(lcp->ld, result); e != NULL; e = ldap_next_entry(lcp->ld, e)) { uschar *new_dn; BOOL insert_space = FALSE; DEBUG(D_lookup) debug_printf("LDAP entry loop\n"); rescount++; /* Count results */ /* Results for multiple entries values are separated by newlines. */ if (data != NULL) data = string_cat(data, &size, &ptr, US"\n", 1); /* Get the DN from the last result. */ new_dn = US ldap_get_dn(lcp->ld, e); if (new_dn != NULL) { if (dn != NULL) { #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2 ldap_memfree(dn); #else /* OPENLDAP 1, UMich, Solaris */ free(dn); #endif } /* Save for later */ dn = new_dn; } /* If the data we want is actually the DN rather than any attribute values, (an "ldapdn" search) add it to the data string. If there are multiple entries, the DNs will be concatenated, but we test for this case below, as for SEARCH_LDAP_SINGLE, and give an error. */ if (search_type == SEARCH_LDAP_DN) /* Do not amalgamate these into one */ { /* condition, because of the else */ if (new_dn != NULL) /* below, that's for the first only */ { data = string_cat(data, &size, &ptr, new_dn, Ustrlen(new_dn)); data[ptr] = 0; attribute_found = TRUE; } } /* Otherwise, loop through the entry, grabbing attribute values. If there's only one attribute being retrieved, no attribute name is given, and the result is not quoted. Multiple values are separated by (comma, space). If more than one attribute is being retrieved, the data is given as a sequence of name=value pairs, with the value always in quotes. If there are multiple values, they are given within the quotes, comma separated. */ else for (attr = US ldap_first_attribute(lcp->ld, e, &ber); attr != NULL; attr = US ldap_next_attribute(lcp->ld, e, ber)) { if (attr[0] != 0) { /* Get array of values for this attribute. */ if ((firstval = values = USS ldap_get_values(lcp->ld, e, CS attr)) != NULL) { if (attr_count != 1) { if (insert_space) data = string_cat(data, &size, &ptr, US" ", 1); else insert_space = TRUE; data = string_cat(data, &size, &ptr, attr, Ustrlen(attr)); data = string_cat(data, &size, &ptr, US"=\"", 2); } while (*values != NULL) { uschar *value = *values; int len = Ustrlen(value); DEBUG(D_lookup) debug_printf("LDAP attr loop %s:%s\n", attr, value); if (values != firstval) data = string_cat(data, &size, &ptr, US", ", 2); /* For multiple attributes, the data is in quotes. We must escape internal quotes, backslashes, newlines. */ if (attr_count != 1) { int j; for (j = 0; j < len; j++) { if (value[j] == '\n') data = string_cat(data, &size, &ptr, US"\\n", 2); else { if (value[j] == '\"' || value[j] == '\\') data = string_cat(data, &size, &ptr, US"\\", 1); data = string_cat(data, &size, &ptr, value+j, 1); } } } /* For single attributes, copy the value verbatim */ else data = string_cat(data, &size, &ptr, value, len); /* Move on to the next value */ values++; attribute_found = TRUE; } /* Closing quote at the end of the data for a named attribute. */ if (attr_count != 1) data = string_cat(data, &size, &ptr, US"\"", 1); /* Free the values */ ldap_value_free(CSS firstval); } } #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2 /* Netscape and OpenLDAP2 LDAP's attrs are dynamically allocated and need to be freed. UMich LDAP stores them in static storage and does not require this. */ ldap_memfree(attr); #endif } /* End "for" loop for extracting attributes from an entry */ } /* End "for" loop for extracting entries from a result */ /* Free the result */ ldap_msgfree(result); result = NULL; } /* End "while" loop for multiple results */ /* Terminate the dynamic string that we have built and reclaim unused store */ if (data != NULL) { data[ptr] = 0; store_reset(data + ptr + 1); } /* Copy the last dn into eldap_dn */ if (dn != NULL) { eldap_dn = string_copy(dn); #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2 ldap_memfree(dn); #else /* OPENLDAP 1, UMich, Solaris */ free(dn); #endif } DEBUG(D_lookup) debug_printf("search ended by ldap_result yielding %d\n",rc); if (rc == 0) { *errmsg = US"ldap_result timed out"; goto RETURN_ERROR; } /* A return code of -1 seems to mean "ldap_result failed internally or couldn't provide you with a message". Other error states seem to exist where ldap_result() didn't give us any message from the server at all, leaving result set to NULL. Apparently, "the error parameters of the LDAP session handle will be set accordingly". That's the best we can do to retrieve an error status; we can't use functions like ldap_result2error because they parse a message from the server, which we didn't get. Annoyingly, the different implementations of LDAP have gone for different methods of handling error codes and generating error messages. */ if (rc == -1 || result == NULL) { int err; DEBUG(D_lookup) debug_printf("ldap_result failed\n"); #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2 ldap_get_option(lcp->ld, LDAP_OPT_ERROR_NUMBER, &err); *errmsg = string_sprintf("ldap_result failed: %d, %s", err, ldap_err2string(err)); #elif defined LDAP_LIB_NETSCAPE /* Dubious (surely 'matched' is spurious here?) */ (void)ldap_get_lderrno(lcp->ld, &matched, &error1); *errmsg = string_sprintf("ldap_result failed: %s (%s)", error1, matched); #else /* UMich LDAP aka OpenLDAP 1.x */ *errmsg = string_sprintf("ldap_result failed: %d, %s", lcp->ld->ld_errno, ldap_err2string(lcp->ld->ld_errno)); #endif goto RETURN_ERROR; } /* A return code that isn't -1 doesn't necessarily mean there were no problems with the search. The message must be an LDAP_RES_SEARCH_RESULT or LDAP_RES_SEARCH_REFERENCE or else it's something we can't handle. Some versions of LDAP do not define LDAP_RES_SEARCH_REFERENCE (LDAP v1 is one, it seems). So we don't provide that functionality when we can't. :-) */ if (rc != LDAP_RES_SEARCH_RESULT #ifdef LDAP_RES_SEARCH_REFERENCE && rc != LDAP_RES_SEARCH_REFERENCE #endif ) { *errmsg = string_sprintf("ldap_result returned unexpected code %d", rc); goto RETURN_ERROR; } /* We have a result message from the server. This doesn't yet mean all is well. We need to parse the message to find out exactly what's happened. */ #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2 ldap_rc = rc; ldap_parse_rc = ldap_parse_result(lcp->ld, result, &rc, CSS &matched, CSS &error2, NULL, NULL, 0); DEBUG(D_lookup) debug_printf("ldap_parse_result: %d\n", ldap_parse_rc); if (ldap_parse_rc < 0 && (ldap_parse_rc != LDAP_NO_RESULTS_RETURNED #ifdef LDAP_RES_SEARCH_REFERENCE || ldap_rc != LDAP_RES_SEARCH_REFERENCE #endif )) { *errmsg = string_sprintf("ldap_parse_result failed %d", ldap_parse_rc); goto RETURN_ERROR; } error1 = US ldap_err2string(rc); #elif defined LDAP_LIB_NETSCAPE /* Dubious (it doesn't reference 'result' at all!) */ rc = ldap_get_lderrno(lcp->ld, &matched, &error1); #else /* UMich LDAP aka OpenLDAP 1.x */ rc = ldap_result2error(lcp->ld, result, 0); error1 = ldap_err2string(rc); error2 = lcp->ld->ld_error; matched = lcp->ld->ld_matched; #endif /* Process the status as follows: (1) If we get LDAP_SIZELIMIT_EXCEEDED, just carry on, to return the truncated result list. (2) If we get LDAP_RES_SEARCH_REFERENCE, also just carry on. This was a submitted patch that is reported to "do the right thing" with Solaris LDAP libraries. (The problem it addresses apparently does not occur with Open LDAP.) (3) The range of errors defined by LDAP_NAME_ERROR generally mean "that object does not, or cannot, exist in the database". For those cases we fail the lookup. (4) All other non-successes here are treated as some kind of problem with the lookup, so return DEFER (which is the default in error_yield). */ DEBUG(D_lookup) debug_printf("ldap_parse_result yielded %d: %s\n", rc, ldap_err2string(rc)); if (rc != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED #ifdef LDAP_RES_SEARCH_REFERENCE && rc != LDAP_RES_SEARCH_REFERENCE #endif ) { *errmsg = string_sprintf("LDAP search failed - error %d: %s%s%s%s%s", rc, (error1 != NULL)? error1 : US"", (error2 != NULL && error2[0] != 0)? US"/" : US"", (error2 != NULL)? error2 : US"", (matched != NULL && matched[0] != 0)? US"/" : US"", (matched != NULL)? matched : US""); #if defined LDAP_NAME_ERROR if (LDAP_NAME_ERROR(rc)) #elif defined NAME_ERROR /* OPENLDAP1 calls it this */ if (NAME_ERROR(rc)) #else if (rc == LDAP_NO_SUCH_OBJECT) #endif { DEBUG(D_lookup) debug_printf("lookup failure forced\n"); error_yield = FAIL; } goto RETURN_ERROR; } /* The search succeeded. Check if we have too many results */ if (search_type != SEARCH_LDAP_MULTIPLE && rescount > 1) { *errmsg = string_sprintf("LDAP search: more than one entry (%d) was returned " "(filter not specific enough?)", rescount); goto RETURN_ERROR_BREAK; } /* Check if we have too few (zero) entries */ if (rescount < 1) { *errmsg = string_sprintf("LDAP search: no results"); error_yield = FAIL; goto RETURN_ERROR_BREAK; } /* If an entry was found, but it had no attributes, we behave as if no entries were found, that is, the lookup failed. */ if (!attribute_found) { *errmsg = US"LDAP search: found no attributes"; error_yield = FAIL; goto RETURN_ERROR; } /* Otherwise, it's all worked */ DEBUG(D_lookup) debug_printf("LDAP search: returning: %s\n", data); *res = data; RETURN_OK: if (result != NULL) ldap_msgfree(result); ldap_free_urldesc(ludp); return OK; /* Error returns */ RETURN_ERROR_BREAK: *defer_break = TRUE; RETURN_ERROR: DEBUG(D_lookup) debug_printf("%s\n", *errmsg); RETURN_ERROR_NOMSG: if (result != NULL) ldap_msgfree(result); if (ludp != NULL) ldap_free_urldesc(ludp); #if defined LDAP_LIB_OPENLDAP2 if (error2 != NULL) ldap_memfree(error2); if (matched != NULL) ldap_memfree(matched); #endif return error_yield; }
int main( int argc, char **argv ) { LDAP *ld; LDAPMessage *result, *e; BerElement *ber; char *host, *a, *dn; char **vals; int i; int rc; int finished; int msgid; int num_entries = 0; struct timeval zerotime; if ( argc > 1 ) { host = argv[1]; } else { host = MY_HOST; } zerotime.tv_sec = zerotime.tv_usec = 0L; if ( prldap_install_routines( NULL, 1 /* shared */ ) != LDAP_SUCCESS ) { ldap_perror( NULL, "prldap_install_routines" ); return( 1 ); } /* get a handle to an LDAP connection */ if ( (ld = ldap_init( host, MY_PORT )) == NULL ) { perror( host ); return( 1 ); } /* authenticate to the directory as nobody */ if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_simple_bind_s" ); return( 1 ); } /* search for all entries with surname of Jensen */ if (( msgid = ldap_search( ld, MY_SEARCHBASE, LDAP_SCOPE_SUBTREE, MY_FILTER, NULL, 0 )) < 0 ) { ldap_perror( ld, "ldap_search" ); return( 1 ); } /* Loop, polling for results until finished */ finished = 0; while ( !finished ) { /* * Poll for results. We call ldap_result with the "all" argument * set to LDAP_MSG_ONE. This causes ldap_result() to return exactly one * entry if at least one entry is available. This allows us to * display the entries as they are received. */ result = NULL; rc = ldap_result( ld, msgid, LDAP_MSG_ONE, &zerotime, &result ); switch ( rc ) { case -1: /* some error occurred */ ldap_perror( ld, "ldap_result" ); return( 1 ); case 0: /* Timeout was exceeded. No entries are ready for retrieval. */ if ( result != NULL ) { ldap_msgfree( result ); } break; default: /* * Either an entry is ready for retrieval, or all entries have * been retrieved. */ if (( e = ldap_first_entry( ld, result )) == NULL ) { /* All done */ finished = 1; if ( result != NULL ) { ldap_msgfree( result ); } continue; } /* for each entry print out name + all attrs and values */ num_entries++; if (( dn = ldap_get_dn( ld, e )) != NULL ) { printf( "dn: %s\n", dn ); ldap_memfree( dn ); } for ( a = ldap_first_attribute( ld, e, &ber ); a != NULL; a = ldap_next_attribute( ld, e, ber ) ) { 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 ); } printf( "\n" ); ldap_msgfree( result ); } /* Do other work here while you are waiting... */ do_other_work(); } /* All done. Print a summary. */ printf( "%d entries retrieved. I counted to %ld " "while I was waiting.\n", num_entries, global_counter ); ldap_unbind( ld ); return( 0 ); }
sInt32 CLDAPNode::GetSchemaMessage ( LDAP *inHost, int inSearchTO, LDAPMessage **outResultMsg ) { sInt32 siResult = eDSNoErr; bool bResultFound = false; int ldapMsgId = 0; LDAPMessage *result = nil; int ldapReturnCode = 0; char *sattrs[2] = {"subschemasubentry",NULL}; char *attrs[2] = {"objectclasses",NULL}; char *subschemaDN = nil; BerElement *ber; struct berval **bValues; char *pAttr = nil; try { //search for the specific LDAP record subschemasubentry at the rootDSE which contains //the "dn" of the subschema record // here is the call to the LDAP server asynchronously which requires // host handle, search base, search scope(LDAP_SCOPE_SUBTREE for all), search filter, // attribute list (NULL for all), return attrs values flag // Note: asynchronous call is made so that a MsgId can be used for future calls // This returns us the message ID which is used to query the server for the results if ( (ldapMsgId = ldap_search( inHost, "", LDAP_SCOPE_BASE, "(objectclass=*)", sattrs, 0) ) == -1 ) { bResultFound = false; } else { bResultFound = true; //retrieve the actual LDAP record data for use internally //useful only from the read-only perspective if (inSearchTO == 0) { ldapReturnCode = ldap_result(inHost, ldapMsgId, 0, NULL, &result); } else { struct timeval tv; tv.tv_sec = inSearchTO; tv.tv_usec = 0; ldapReturnCode = ldap_result(inHost, ldapMsgId, 0, &tv, &result); } } if ( (bResultFound) && ( ldapReturnCode == LDAP_RES_SEARCH_ENTRY ) ) { siResult = eDSNoErr; //get the subschemaDN here //parse the attributes in the result - should only be one ie. subschemasubentry for ( pAttr = ldap_first_attribute (inHost, result, &ber ); pAttr != NULL; pAttr = ldap_next_attribute(inHost, result, ber ) ) { if (( bValues = ldap_get_values_len (inHost, result, pAttr )) != NULL) { // should be only one value of the attribute if ( bValues[0] != NULL ) { subschemaDN = (char *) calloc(1, bValues[0]->bv_len + 1); strcpy(subschemaDN,bValues[0]->bv_val); } ldap_value_free_len(bValues); } // if bValues = ldap_get_values_len ... if (pAttr != nil) { ldap_memfree( pAttr ); } } // for ( loop over ldap_next_attribute ) if (ber != nil) { ber_free( ber, 0 ); } ldap_msgfree( result ); result = nil; } // if bResultFound and ldapReturnCode okay else if (ldapReturnCode == LDAP_TIMEOUT) { siResult = eDSServerTimeout; if ( result != nil ) { ldap_msgfree( result ); result = nil; } } else { siResult = eDSRecordNotFound; if ( result != nil ) { ldap_msgfree( result ); result = nil; } } if (subschemaDN != nil) { //here we call to get the actual subschema record //here is the call to the LDAP server asynchronously which requires // host handle, search base, search scope(LDAP_SCOPE_SUBTREE for all), search filter, // attribute list (NULL for all), return attrs values flag // Note: asynchronous call is made so that a MsgId can be used for future calls // This returns us the message ID which is used to query the server for the results if ( (ldapMsgId = ldap_search( inHost, subschemaDN, LDAP_SCOPE_BASE, "(objectclass=subSchema)", attrs, 0) ) == -1 ) { bResultFound = false; } else { bResultFound = true; //retrieve the actual LDAP record data for use internally //useful only from the read-only perspective //KW when write capability is added, we will need to re-read the result after a write if (inSearchTO == 0) { ldapReturnCode = ldap_result(inHost, ldapMsgId, 0, NULL, &result); } else { struct timeval tv; tv.tv_sec = inSearchTO; tv.tv_usec = 0; ldapReturnCode = ldap_result(inHost, ldapMsgId, 0, &tv, &result); } } free(subschemaDN); subschemaDN = nil; if ( (bResultFound) && ( ldapReturnCode == LDAP_RES_SEARCH_ENTRY ) ) { siResult = eDSNoErr; } // if bResultFound and ldapReturnCode okay else if (ldapReturnCode == LDAP_TIMEOUT) { siResult = eDSServerTimeout; if ( result != nil ) { ldap_msgfree( result ); result = nil; } } else { siResult = eDSRecordNotFound; if ( result != nil ) { ldap_msgfree( result ); result = nil; } } } } catch ( sInt32 err ) { siResult = err; } if (result != nil) { *outResultMsg = result; } return( siResult ); } // GetSchemaMessage
extern int ldap_search_a(char *ldap_host, char *root_dn, char *root_pw, char *base, char *filter) { LDAP *ld; int result; int auth_method = LDAP_AUTH_SIMPLE; int desired_version = LDAP_VERSION3; BerElement* ber; LDAPMessage* msg; LDAPMessage* entry; char* errstring; char* dn = NULL; char* attr; char** vals; int i, msgid; struct timeval tm; if ((ld = ldap_init(ldap_host, LDAP_PORT)) == NULL ) { perror( "ldap_init failed" ); exit( EXIT_FAILURE ); } /* set the LDAP version to be 3 */ if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version) != LDAP_OPT_SUCCESS) { ldap_perror(ld, "ldap_set_option"); exit(EXIT_FAILURE); } if (ldap_bind_s(ld, root_dn, root_pw, auth_method) != LDAP_SUCCESS ) { ldap_perror( ld, "ldap_bind" ); exit( EXIT_FAILURE ); } /* ldap_search() returns -1 if there is an error, otherwise the msgid */ if ((msgid = ldap_search(ld, base, LDAP_SCOPE_SUBTREE, filter, NULL, 0)) == -1) { ldap_perror( ld, "ldap_search" ); exit(EXIT_FAILURE); } /* block forever */ result = ldap_result(ld, msgid, 1, NULL, &msg); switch(result) { case(-1): ldap_perror(ld, "ldap_result"); exit(EXIT_FAILURE); break; case(0): printf("Timeout exceeded in ldap_result()"); exit(EXIT_FAILURE); break; case(LDAP_RES_SEARCH_RESULT): printf("Search result returned\n"); break; default: printf("Unknown result : %x\n", result); exit(EXIT_FAILURE); break; } printf("The number of entries returned was %d\n\n", ldap_count_entries(ld, msg)); /* Iterate through the returned entries */ for(entry = ldap_first_entry(ld, msg); entry != NULL; entry = ldap_next_entry(ld, entry)) { if((dn = ldap_get_dn(ld, entry)) != NULL) { printf("Returned dn: %s\n", dn); ldap_memfree(dn); } for( attr = ldap_first_attribute(ld, entry, &ber); attr != NULL; attr = ldap_next_attribute(ld, entry, ber)) { if ((vals = ldap_get_values(ld, entry, attr)) != NULL) { for(i = 0; vals[i] != NULL; i++) { printf("%s:%s\n", attr, vals[i]); } ldap_value_free(vals); } ldap_memfree(attr); } if (ber != NULL) { ber_free(ber,0); } printf("\n"); } /* clean up */ ldap_msgfree(msg); result = ldap_unbind_s(ld); if (result != 0) { fprintf(stderr, "ldap_unbind_s: %s\n", ldap_err2string(result)); exit( EXIT_FAILURE ); } return EXIT_SUCCESS; }