1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2004 The OpenLDAP Foundation.
6 * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7 * Portions Copyright 1998-2001 Net Boolean Incorporated.
8 * Portions Copyright 2001-2003 IBM Corporation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms are permitted
23 * provided that this notice is preserved and that due credit is given
24 * to the University of Michigan at Ann Arbor. The name of the
25 * University may not be used to endorse or promote products derived
26 * from this software without specific prior written permission. This
27 * software is provided ``as is'' without express or implied warranty.
30 * This work was originally developed by the University of Michigan
31 * (as part of U-MICH LDAP). Additional significant contributors
43 #include <ac/stdlib.h>
46 #include <ac/string.h>
47 #include <ac/unistd.h>
54 #ifdef HAVE_SYS_TYPES_H
55 #include <sys/types.h>
65 #include "lutil_ldap.h"
66 #include "ldap_defaults.h"
73 static int scope = LDAP_SCOPE_SUBTREE;
74 static int deref = -1;
76 static int timelimit = -1;
77 static int sizelimit = -1;
79 static char *def_tmpdir;
80 static char *def_urlpre;
82 #if defined(__CYGWIN__) || defined(__MINGW32__)
83 /* Turn off commandline globbing, otherwise you cannot search for
92 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
93 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
94 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
95 fprintf( stderr, _(" which may include:\n"));
96 fprintf( stderr, _(" 1.1 no attributes\n"));
97 fprintf( stderr, _(" * all user attributes\n"));
98 fprintf( stderr, _(" + all operational attributes\n"));
101 fprintf( stderr, _("Search options:\n"));
102 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
103 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
104 fprintf( stderr, _(" -b basedn base dn for search\n"));
105 fprintf( stderr, _(" -E [!]<ctrl>[=<ctrlparam>] search extensions (! indicates criticality)\n"));
106 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
107 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
109 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
110 #ifdef LDAP_CONTROL_PAGEDRESULTS
111 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
113 #ifdef LDAP_CONTROL_SUBENTRIES
114 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
116 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
117 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
118 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
119 fprintf( stderr, _(" -l limit time limit (in seconds) for search\n"));
120 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
121 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
122 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
123 fprintf( stderr, _(" and version\n"));
124 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
125 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
126 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
127 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
128 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
129 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
130 fprintf( stderr, _(" -z limit size limit (in entries) for search\n"));
132 exit( EXIT_FAILURE );
135 static void print_entry LDAP_P((
140 static void print_reference(
142 LDAPMessage *reference );
144 static void print_extended(
146 LDAPMessage *extended );
148 static void print_partial(
150 LDAPMessage *partial );
152 static int print_result(
157 static void print_ctrls(
158 LDAPControl **ctrls );
160 static int write_ldif LDAP_P((
166 static int dosearch LDAP_P((
174 LDAPControl **sctrls,
175 LDAPControl **cctrls,
176 struct timeval *timeout,
179 static char *tmpdir = NULL;
180 static char *urlpre = NULL;
181 static char *base = NULL;
182 static char *sortattr = NULL;
183 static int includeufn, vals2tmp = 0, ldif = 0;
185 static int subentries = 0, valuesReturnFilter = 0;
186 static char *vrFilter = NULL;
188 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
189 static int domainScope = 0;
192 static int ldapsync = 0;
193 static struct berval sync_cookie = { 0, NULL };
194 static int sync_slimit = -1;
196 #ifdef LDAP_CONTROL_PAGEDRESULTS
197 static int pagedResults = 0;
198 static int pagePrompt = 1;
199 static ber_int_t pageSize = 0;
200 static ber_int_t entriesLeft = 0;
201 static ber_int_t morePagedResults = 1;
202 static struct berval cookie = { 0, NULL };
203 static int npagedresponses;
204 static int npagedentries;
205 static int npagedreferences;
206 static int npagedextended;
207 static int npagedpartial;
209 static int parse_page_control(
212 struct berval *cookie );
220 if (*LDAP_DIRSEP != '/') {
221 for (p = url; *p; p++) {
222 if (*p == *LDAP_DIRSEP)
229 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
230 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
233 handle_private_option( int i )
236 char *control, *cvalue;
238 case 'a': /* set alias deref option */
239 if ( strcasecmp( optarg, "never" ) == 0 ) {
240 deref = LDAP_DEREF_NEVER;
241 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
242 deref = LDAP_DEREF_SEARCHING;
243 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
244 deref = LDAP_DEREF_FINDING;
245 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
246 deref = LDAP_DEREF_ALWAYS;
248 fprintf( stderr, _("alias deref should be never, search, find, or always\n") );
252 case 'A': /* retrieve attribute names only -- no values */
255 case 'b': /* search base */
256 base = strdup( optarg );
258 case 'E': /* search extensions */
259 if( protocol == LDAP_VERSION2 ) {
260 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
262 exit( EXIT_FAILURE );
265 /* should be extended to support comma separated list of
266 * [!]key[=value] parameters, e.g. -E !foo,bar=567
271 if( optarg[0] == '!' ) {
276 control = strdup( optarg );
277 if ( (cvalue = strchr( control, '=' )) != NULL ) {
281 if ( strcasecmp( control, "mv" ) == 0 ) {
282 /* ValuesReturnFilter control */
283 if( valuesReturnFilter ) {
284 fprintf( stderr, _("ValuesReturnFilter previously specified\n"));
285 exit( EXIT_FAILURE );
287 valuesReturnFilter= 1 + crit;
289 if ( cvalue == NULL ) {
291 _("missing filter in ValuesReturnFilter control\n"));
292 exit( EXIT_FAILURE );
296 protocol = LDAP_VERSION3;
298 #ifdef LDAP_CONTROL_PAGEDRESULTS
299 } else if ( strcasecmp( control, "pr" ) == 0 ) {
301 /* PagedResults control */
302 if ( pagedResults != 0 ) {
303 fprintf( stderr, _("PagedResultsControl previously specified\n") );
304 exit( EXIT_FAILURE );
307 if( cvalue != NULL ) {
310 promptp = strchr( cvalue, '/' );
311 if ( promptp != NULL ) {
313 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
315 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
318 fprintf( stderr, _("Invalid value for PagedResultsControl, %s/%s.\n"), cvalue, promptp);
319 exit( EXIT_FAILURE );
322 num = sscanf( cvalue, "%d", &tmp );
324 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), cvalue);
325 exit( EXIT_FAILURE );
328 fprintf( stderr, _("Invalid value for PagedResultsControl.\n"), cvalue);
329 exit( EXIT_FAILURE );
331 pageSize = (ber_int_t) tmp;
332 pagedResults = 1 + crit;
335 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
336 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
339 _("domainScope control previously specified\n"));
340 exit( EXIT_FAILURE );
342 if( cvalue != NULL ) {
344 _("domainScope: no control value expected\n") );
348 domainScope = 1 + crit;
350 #ifdef LDAP_CONTROL_SUBENTRIES
351 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
353 fprintf( stderr, _("subentries control previously specified\n"));
354 exit( EXIT_FAILURE );
356 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
358 } else if ( strcasecmp( cvalue, "false") == 0 ) {
362 _("subentries control value \"%s\" invalid\n"),
364 exit( EXIT_FAILURE );
366 if( crit ) subentries *= -1;
369 } else if ( strcasecmp( control, "sync" ) == 0 ) {
373 fprintf( stderr, _("ldap sync control previously specified\n") );
374 exit( EXIT_FAILURE );
376 if ( cvalue == NULL ) {
378 _("missing specification of ldap sync control\n"));
379 exit( EXIT_FAILURE );
381 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
382 ldapsync = LDAP_SYNC_REFRESH_ONLY;
383 cookiep = strchr( cvalue, '/' );
384 if ( cookiep != NULL ) {
386 if ( *cookiep != '\0' ) {
387 ber_str2bv( cookiep, 0, 0, &sync_cookie );
390 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
391 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
392 cookiep = strchr( cvalue, '/' );
393 if ( cookiep != NULL ) {
397 slimitp = strchr( cvalue, '/' );
398 if ( slimitp != NULL ) {
401 if ( cookiep != NULL && *cookiep != '\0' )
402 ber_str2bv( cookiep, 0, 0, &sync_cookie );
403 if ( slimitp != NULL && *slimitp != '\0' )
404 sync_slimit = atoi( slimitp );
407 _("ldap sync control value \"%s\" invalid\n"),
409 exit( EXIT_FAILURE );
411 if ( crit ) ldapsync *= -1;
414 fprintf( stderr, _("Invalid search extension name: %s\n"), control );
418 case 'F': /* uri prefix */
419 if( urlpre ) free( urlpre );
420 urlpre = strdup( optarg );
422 case 'l': /* time limit */
423 timelimit = atoi( optarg );
424 if( timelimit < 0 ) {
425 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
427 exit( EXIT_FAILURE );
430 case 'L': /* print entries in LDIF format */
433 case 's': /* search scope */
434 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
435 scope = LDAP_SCOPE_BASE;
436 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
437 scope = LDAP_SCOPE_ONELEVEL;
438 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
439 || ( strcasecmp( optarg, "children" ) == 0 ))
441 scope = LDAP_SCOPE_SUBORDINATE;
442 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
443 scope = LDAP_SCOPE_SUBTREE;
445 fprintf( stderr, _("scope should be base, one, or sub\n") );
449 case 'S': /* sort attribute */
450 sortattr = strdup( optarg );
452 case 't': /* write attribute values to TMPDIR files */
455 case 'T': /* tmpdir */
456 if( tmpdir ) free( tmpdir );
457 tmpdir = strdup( optarg );
459 case 'u': /* include UFN */
462 case 'z': /* size limit */
463 sizelimit = atoi( optarg );
473 private_conn_setup( LDAP *ld )
476 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
478 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
479 exit( EXIT_FAILURE );
481 if (timelimit != -1 &&
482 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
484 fprintf( stderr, _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
485 exit( EXIT_FAILURE );
487 if (sizelimit != -1 &&
488 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
490 fprintf( stderr, _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
491 exit( EXIT_FAILURE );
497 main( int argc, char **argv )
499 char *filtpattern, **attrs = NULL, line[BUFSIZ];
503 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
505 BerElement *syncber = NULL;
506 struct berval *syncbvalp = NULL;
510 #ifdef LDAP_CONTROL_PAGEDRESULTS
511 npagedresponses = npagedentries = npagedreferences =
512 npagedextended = npagedpartial = 0;
515 prog = lutil_progname( "ldapsearch", argc, argv );
517 lutil_log_initialize(argc, argv);
519 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
520 (def_tmpdir = getenv("TMP")) == NULL &&
521 (def_tmpdir = getenv("TEMP")) == NULL )
523 def_tmpdir = LDAP_TMPDIR;
527 def_tmpdir = LDAP_TMPDIR;
529 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
531 if( def_urlpre == NULL ) {
536 sprintf( def_urlpre, "file:///%s/",
537 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
539 urlize( def_urlpre );
541 tool_args( argc, argv );
543 if (( argc - optind < 1 ) ||
544 ( *argv[optind] != '(' /*')'*/ &&
545 ( strchr( argv[optind], '=' ) == NULL ) ) )
547 filtpattern = "(objectclass=*)";
549 filtpattern = strdup( argv[optind++] );
552 if ( argv[optind] != NULL ) {
553 attrs = &argv[optind];
556 if ( infile != NULL ) {
557 if ( infile[0] == '-' && infile[1] == '\0' ) {
559 } else if (( fp = fopen( infile, "r" )) == NULL ) {
565 if ( tmpdir == NULL ) {
568 if ( urlpre == NULL )
572 if( urlpre == NULL ) {
573 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
575 if( urlpre == NULL ) {
580 sprintf( urlpre, "file:///%s/",
581 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
589 ld = tool_conn_setup( 0, &private_conn_setup );
591 if ( pw_file || want_bindpw ) {
593 rc = lutil_get_filed_password( pw_file, &passwd );
594 if( rc ) return EXIT_FAILURE;
596 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
597 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
604 if ( assertion || authzid || manageDSAit || noop
605 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
608 #ifdef LDAP_CONTROL_PAGEDRESULTS
612 || subentries || valuesReturnFilter )
618 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
620 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
621 c[i].ldctl_value.bv_val = NULL;
622 c[i].ldctl_value.bv_len = 0;
623 c[i].ldctl_iscritical = domainScope > 1;
628 #ifdef LDAP_CONTROL_SUBENTRIES
630 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
634 err = ber_printf( seber, "{b}", abs(subentries) == 1 ? 0 : 1 );
636 ber_free( seber, 1 );
637 fprintf( stderr, _("Subentries control encoding error!\n") );
641 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
645 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
646 c[i].ldctl_iscritical = subentries < 1;
652 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
656 if ( sync_cookie.bv_len == 0 ) {
657 err = ber_printf( syncber, "{e}", abs(ldapsync) );
659 err = ber_printf( syncber, "{eO}", abs(ldapsync),
663 if ( err == LBER_ERROR ) {
664 ber_free( syncber, 1 );
665 fprintf( stderr, _("ldap sync control encoding error!\n") );
669 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
673 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
674 c[i].ldctl_value = (*syncbvalp);
675 c[i].ldctl_iscritical = ldapsync < 0;
679 if ( valuesReturnFilter ) {
680 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
684 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
685 ber_free( vrber, 1 );
686 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
690 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
694 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
695 c[i].ldctl_iscritical = valuesReturnFilter > 1;
699 #ifdef LDAP_CONTROL_PAGEDRESULTS
700 if ( pagedResults ) {
701 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
705 ber_printf( prber, "{iO}", pageSize, &cookie );
706 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
710 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
711 c[i].ldctl_iscritical = pagedResults > 1;
716 tool_server_controls( ld, c, i );
718 ber_free( seber, 1 );
719 ber_free( vrber, 1 );
720 ber_free( prber, 1 );
724 fprintf( stderr, _("filter%s: %s\nrequesting: "),
725 infile != NULL ? _(" pattern") : "",
728 if ( attrs == NULL ) {
729 fprintf( stderr, _("ALL") );
731 for ( i = 0; attrs[ i ] != NULL; ++i ) {
732 fprintf( stderr, "%s ", attrs[ i ] );
735 fprintf( stderr, "\n" );
739 printf( _("# extended LDIF\n") );
740 } else if ( ldif < 3 ) {
741 printf( _("version: %d\n\n"), 1 );
746 printf(_("# LDAPv%d\n"), protocol);
747 printf(_("# base <%s> with scope %s\n"),
749 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
750 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
751 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
753 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
755 printf(_("# requesting: "));
757 if ( attrs == NULL ) {
760 for ( i = 0; attrs[ i ] != NULL; ++i ) {
761 printf( "%s ", attrs[ i ] );
766 printf(_("\n# with manageDSAit %scontrol"),
767 manageDSAit > 1 ? _("critical ") : "" );
770 printf(_("\n# with noop %scontrol"),
771 noop > 1 ? _("critical ") : "" );
774 printf(_("\n# with subentries %scontrol: %s"),
775 subentries < 0 ? _("critical ") : "",
776 abs(subentries) == 1 ? "false" : "true" );
778 if ( valuesReturnFilter ) {
779 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
780 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
782 #ifdef LDAP_CONTROL_PAGEDRESULTS
784 printf(_("\n# with pagedResults %scontrol: size=%d"),
785 (pagedResults > 1) ? _("critical ") : "",
790 printf( _("\n#\n\n") );
793 if ( infile == NULL ) {
794 rc = dosearch( ld, base, scope, NULL, filtpattern,
795 attrs, attrsonly, NULL, NULL, NULL, -1 );
800 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
801 line[ strlen( line ) - 1 ] = '\0';
807 rc = dosearch( ld, base, scope, filtpattern, line,
808 attrs, attrsonly, NULL, NULL, NULL, -1 );
815 #ifdef LDAP_CONTROL_PAGEDRESULTS
816 if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
818 int i, moreEntries, tmpSize;
820 /* Loop to get the next pages when
821 * enter is pressed on the terminal.
823 if ( pagePrompt != 0 ) {
824 if ( entriesLeft > 0 ) {
825 printf( _("Estimate entries: %d\n"), entriesLeft );
827 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
830 moreEntries = getchar();
831 while ( moreEntries != EOF && moreEntries != '\n' ) {
832 if ( i < (int)sizeof(buf) - 1 ) {
833 buf[i] = moreEntries;
836 moreEntries = getchar();
840 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
841 int num = sscanf( buf, "%d", &tmpSize );
843 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
847 pageSize = (ber_int_t)tmpSize;
855 ldap_unbind_ext( ld, NULL, NULL );
856 #ifdef HAVE_CYRUS_SASL
860 ldap_pvt_tls_destroy();
874 LDAPControl **sctrls,
875 LDAPControl **cctrls,
876 struct timeval *timeout,
886 LDAPMessage *res, *msg;
889 struct berval *retdata = NULL;
890 int nresponses_psearch = -1;
891 int cancel_msgid = -1;
893 if( filtpatt != NULL ) {
894 filter = malloc( strlen( filtpatt ) + strlen( value ) );
895 if( filter == NULL ) {
900 sprintf( filter, filtpatt, value );
903 fprintf( stderr, _("filter: %s\n"), filter );
907 printf( _("#\n# filter: %s\n#\n"), filter );
918 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
919 sctrls, cctrls, timeout, sizelimit, &msgid );
921 if ( filtpatt != NULL ) {
925 if( rc != LDAP_SUCCESS ) {
926 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
927 prog, ldap_err2string( rc ), rc );
931 nresponses = nentries = nreferences = nextended = npartial = 0;
935 while ((rc = ldap_result( ld, LDAP_RES_ANY,
936 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
940 (void) ldap_sort_entries( ld, &res,
941 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
944 for ( msg = ldap_first_message( ld, res );
946 msg = ldap_next_message( ld, msg ) )
948 if ( nresponses++ ) putchar('\n');
949 if ( nresponses_psearch >= 0 )
950 nresponses_psearch++;
952 switch( ldap_msgtype( msg ) ) {
953 case LDAP_RES_SEARCH_ENTRY:
955 print_entry( ld, msg, attrsonly );
958 case LDAP_RES_SEARCH_REFERENCE:
960 print_reference( ld, msg );
963 case LDAP_RES_EXTENDED:
965 print_extended( ld, msg );
967 if( ldap_msgid( msg ) == 0 ) {
968 /* unsolicited extended operation */
972 if ( cancel_msgid != -1 &&
973 cancel_msgid == ldap_msgid( msg ) ) {
974 printf(_("Cancelled \n"));
975 printf(_("cancel_msgid = %d\n"), cancel_msgid);
980 case LDAP_RES_SEARCH_RESULT:
981 rc = print_result( ld, msg, 1 );
982 #ifdef LDAP_CONTROL_PAGEDRESULTS
983 if ( pageSize != 0 ) {
984 rc = parse_page_control( ld, msg, &cookie );
988 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
994 case LDAP_RES_INTERMEDIATE:
996 ldap_parse_intermediate( ld, msg,
997 &retoid, &retdata, NULL, 0 );
999 nresponses_psearch = 0;
1001 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1002 printf(_("SyncInfo Received\n"));
1003 ldap_memfree( retoid );
1004 ber_bvfree( retdata );
1008 print_partial( ld, msg );
1009 ldap_memfree( retoid );
1010 ber_bvfree( retdata );
1014 if ( ldapsync && sync_slimit != -1 &&
1015 nresponses_psearch >= sync_slimit ) {
1016 BerElement *msgidber = NULL;
1017 struct berval *msgidvalp = NULL;
1018 msgidber = ber_alloc_t(LBER_USE_DER);
1019 ber_printf(msgidber, "{i}", msgid);
1020 ber_flatten(msgidber, &msgidvalp);
1021 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1022 msgidvalp, NULL, NULL, &cancel_msgid);
1023 nresponses_psearch = -1;
1027 ldap_msgfree( res );
1031 ldap_perror( ld, "ldap_result" );
1036 ldap_msgfree( res );
1037 #ifdef LDAP_CONTROL_PAGEDRESULTS
1038 if ( pageSize != 0 ) {
1039 npagedresponses = npagedresponses + nresponses;
1040 npagedentries = npagedentries + nentries;
1041 npagedreferences = npagedreferences + nreferences;
1042 npagedextended = npagedextended + nextended;
1043 npagedpartial = npagedpartial + npartial;
1044 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1045 printf( _("\n# numResponses: %d\n"), npagedresponses );
1046 if( nentries ) printf( _("# numEntries: %d\n"), npagedentries );
1047 if( nextended ) printf( _("# numExtended: %d\n"), npagedextended );
1048 if( npartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1049 if( nreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1054 printf( _("\n# numResponses: %d\n"), nresponses );
1055 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1056 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1057 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1058 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1064 /* This is the proposed new way of doing things.
1065 * It is more efficient, but the API is non-standard.
1074 char tmpfname[ 256 ];
1077 BerElement *ber = NULL;
1078 struct berval bv, *bvals, **bvp = &bvals;
1079 LDAPControl **ctrls = NULL;
1082 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1085 ufn = ldap_dn2ufn( bv.bv_val );
1086 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1088 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1090 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1091 if( rc != LDAP_SUCCESS ) {
1092 fprintf(stderr, _("print_entry: %d\n"), rc );
1093 ldap_perror( ld, "ldap_get_entry_controls" );
1094 exit( EXIT_FAILURE );
1098 print_ctrls( ctrls );
1099 ldap_controls_free( ctrls );
1104 ufn = ldap_dn2ufn( bv.bv_val );
1106 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1109 if( ufn != NULL ) ldap_memfree( ufn );
1111 if ( attrsonly ) bvp = NULL;
1113 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1115 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1117 if (bv.bv_val == NULL) break;
1120 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1122 } else if ( bvals ) {
1123 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1124 if ( vals2tmp > 1 || ( vals2tmp
1125 && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1128 /* write value to file */
1129 snprintf( tmpfname, sizeof tmpfname,
1130 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1131 tmpdir, bv.bv_val );
1134 tmpfd = mkstemp( tmpfname );
1141 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1146 if ( fwrite( bvals[ i ].bv_val,
1147 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1156 snprintf( url, sizeof url, "%s%s", urlpre,
1157 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1160 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1163 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1164 bvals[ i ].bv_val, bvals[ i ].bv_len );
1167 ber_memfree( bvals );
1176 static void print_reference(
1178 LDAPMessage *reference )
1182 LDAPControl **ctrls;
1185 printf(_("# search reference\n"));
1188 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1190 if( rc != LDAP_SUCCESS ) {
1191 ldap_perror(ld, "ldap_parse_reference");
1192 exit( EXIT_FAILURE );
1197 for( i=0; refs[i] != NULL; i++ ) {
1198 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1199 "ref", refs[i], strlen(refs[i]) );
1201 ber_memvfree( (void **) refs );
1205 print_ctrls( ctrls );
1206 ldap_controls_free( ctrls );
1210 static void print_extended(
1212 LDAPMessage *extended )
1215 char *retoid = NULL;
1216 struct berval *retdata = NULL;
1219 printf(_("# extended result response\n"));
1222 rc = ldap_parse_extended_result( ld, extended,
1223 &retoid, &retdata, 0 );
1225 if( rc != LDAP_SUCCESS ) {
1226 ldap_perror(ld, "ldap_parse_extended_result");
1227 exit( EXIT_FAILURE );
1231 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1232 "extended", retoid, retoid ? strlen(retoid) : 0 );
1234 ber_memfree( retoid );
1238 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1239 "data", retdata->bv_val, retdata->bv_len );
1241 ber_bvfree( retdata );
1244 print_result( ld, extended, 0 );
1247 static void print_partial(
1249 LDAPMessage *partial )
1252 char *retoid = NULL;
1253 struct berval *retdata = NULL;
1254 LDAPControl **ctrls = NULL;
1257 printf(_("# extended partial response\n"));
1260 rc = ldap_parse_intermediate( ld, partial,
1261 &retoid, &retdata, &ctrls, 0 );
1263 if( rc != LDAP_SUCCESS ) {
1264 ldap_perror(ld, "ldap_parse_intermediate");
1265 exit( EXIT_FAILURE );
1269 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1270 "partial", retoid, retoid ? strlen(retoid) : 0 );
1273 ber_memfree( retoid );
1277 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1278 "data", retdata->bv_val, retdata->bv_len );
1281 ber_bvfree( retdata );
1285 print_ctrls( ctrls );
1286 ldap_controls_free( ctrls );
1290 static int print_result(
1292 LDAPMessage *result, int search )
1296 char *matcheddn = NULL;
1299 LDAPControl **ctrls = NULL;
1303 printf(_("# search result\n"));
1306 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1310 rc = ldap_parse_result( ld, result,
1311 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1313 if( rc != LDAP_SUCCESS ) {
1314 ldap_perror(ld, "ldap_parse_result");
1315 exit( EXIT_FAILURE );
1320 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1322 } else if ( err != LDAP_SUCCESS ) {
1323 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1329 write_ldif( LDIF_PUT_VALUE,
1330 "matchedDN", matcheddn, strlen(matcheddn) );
1332 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1336 ber_memfree( matcheddn );
1342 write_ldif( LDIF_PUT_TEXT, "text",
1343 text, strlen(text) );
1345 fprintf( stderr, _("Additional information: %s\n"), text );
1349 ber_memfree( text );
1354 for( i=0; refs[i] != NULL; i++ ) {
1356 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1358 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1362 ber_memvfree( (void **) refs );
1366 print_ctrls( ctrls );
1367 ldap_controls_free( ctrls );
1373 static void print_ctrls(
1374 LDAPControl **ctrls )
1377 for(i=0; ctrls[i] != NULL; i++ ) {
1378 /* control: OID criticality base64value */
1379 struct berval *b64 = NULL;
1384 len += strlen( ctrls[i]->ldctl_oid );
1386 /* add enough for space after OID and the critical value itself */
1387 len += ctrls[i]->ldctl_iscritical
1388 ? sizeof("true") : sizeof("false");
1390 /* convert to base64 */
1391 if( ctrls[i]->ldctl_value.bv_len ) {
1392 b64 = ber_memalloc( sizeof(struct berval) );
1394 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1395 ctrls[i]->ldctl_value.bv_len ) + 1;
1396 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1398 b64->bv_len = lutil_b64_ntop(
1399 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1400 ctrls[i]->ldctl_value.bv_len,
1401 b64->bv_val, b64->bv_len );
1405 len += 1 + b64->bv_len;
1408 str = malloc( len + 1 );
1410 strcpy( str, ": " );
1414 strcat( str, ctrls[i]->ldctl_oid );
1415 strcat( str, ctrls[i]->ldctl_iscritical
1416 ? " true" : " false" );
1420 strcat(str, b64->bv_val );
1424 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1425 "control", str, len );
1434 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1438 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1442 fputs( ldif, stdout );
1443 ber_memfree( ldif );
1449 #ifdef LDAP_CONTROL_PAGEDRESULTS
1453 LDAPMessage *result,
1454 struct berval *cookie )
1458 LDAPControl **ctrl = NULL;
1459 LDAPControl *ctrlp = NULL;
1462 struct berval servercookie = { 0, NULL };
1464 rc = ldap_parse_result( ld, result,
1465 &err, NULL, NULL, NULL, &ctrl, 0 );
1467 if( rc != LDAP_SUCCESS ) {
1468 ldap_perror(ld, "ldap_parse_result");
1469 exit( EXIT_FAILURE );
1472 if ( err != LDAP_SUCCESS ) {
1473 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1477 /* Parse the control value
1478 * searchResult ::= SEQUENCE {
1479 * size INTEGER (0..maxInt),
1480 * -- result set size estimate from server - unused
1481 * cookie OCTET STRING
1485 ber = ber_init( &ctrlp->ldctl_value );
1486 if ( ber == NULL ) {
1487 fprintf( stderr, _("Internal error.\n") );
1488 return EXIT_FAILURE;
1491 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1492 ber_dupbv( cookie, &servercookie );
1493 (void) ber_free( ber, 1 );
1495 if( tag == LBER_ERROR ) {
1497 _("Paged results response control could not be decoded.\n") );
1498 return EXIT_FAILURE;
1501 if( entriesLeft < 0 ) {
1503 _("Invalid entries estimate in paged results response.\n") );
1504 return EXIT_FAILURE;
1507 if ( servercookie.bv_len == 0 ) {
1508 morePagedResults = 0;
1511 ldap_controls_free( ctrl );
1514 morePagedResults = 0;