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 [!]<ext>[=<extparam>] 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, or \"none\" or \"max\") 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 #ifdef LDAP_SCOPE_SUBORDINATE
125 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
126 #else /* ! LDAP_SCOPE_SUBORDINATE */
127 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
128 #endif /* ! LDAP_SCOPE_SUBORDINATE */
129 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
130 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
131 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
132 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
133 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
134 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
136 exit( EXIT_FAILURE );
139 static void print_entry LDAP_P((
144 static void print_reference(
146 LDAPMessage *reference );
148 static void print_extended(
150 LDAPMessage *extended );
152 static void print_partial(
154 LDAPMessage *partial );
156 static int print_result(
161 static void print_ctrls(
162 LDAPControl **ctrls );
164 static int write_ldif LDAP_P((
170 static int dosearch LDAP_P((
178 LDAPControl **sctrls,
179 LDAPControl **cctrls,
180 struct timeval *timeout,
183 static char *tmpdir = NULL;
184 static char *urlpre = NULL;
185 static char *base = NULL;
186 static char *sortattr = NULL;
187 static int includeufn, vals2tmp = 0, ldif = 0;
189 static int subentries = 0, valuesReturnFilter = 0;
190 static char *vrFilter = NULL;
192 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
193 static int domainScope = 0;
196 static int ldapsync = 0;
197 static struct berval sync_cookie = { 0, NULL };
198 static int sync_slimit = -1;
200 #ifdef LDAP_CONTROL_PAGEDRESULTS
201 static int pagedResults = 0;
202 static int pagePrompt = 1;
203 static ber_int_t pageSize = 0;
204 static ber_int_t entriesLeft = 0;
205 static ber_int_t morePagedResults = 1;
206 static struct berval page_cookie = { 0, NULL };
207 static int npagedresponses;
208 static int npagedentries;
209 static int npagedreferences;
210 static int npagedextended;
211 static int npagedpartial;
213 static int parse_page_control(
216 struct berval *cookie );
224 if (*LDAP_DIRSEP != '/') {
225 for (p = url; *p; p++) {
226 if (*p == *LDAP_DIRSEP)
233 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
234 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
237 handle_private_option( int i )
240 char *control, *cvalue, *next;
242 case 'a': /* set alias deref option */
243 if ( strcasecmp( optarg, "never" ) == 0 ) {
244 deref = LDAP_DEREF_NEVER;
245 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
246 deref = LDAP_DEREF_SEARCHING;
247 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
248 deref = LDAP_DEREF_FINDING;
249 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
250 deref = LDAP_DEREF_ALWAYS;
253 _("alias deref should be never, search, find, or always\n") );
257 case 'A': /* retrieve attribute names only -- no values */
260 case 'b': /* search base */
261 base = ber_strdup( optarg );
263 case 'E': /* search extensions */
264 if( protocol == LDAP_VERSION2 ) {
265 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
267 exit( EXIT_FAILURE );
270 /* should be extended to support comma separated list of
271 * [!]key[=value] parameters, e.g. -E !foo,bar=567
276 if( optarg[0] == '!' ) {
281 control = ber_strdup( optarg );
282 if ( (cvalue = strchr( control, '=' )) != NULL ) {
286 if ( strcasecmp( control, "mv" ) == 0 ) {
287 /* ValuesReturnFilter control */
288 if( valuesReturnFilter ) {
290 _("ValuesReturnFilter previously specified\n"));
291 exit( EXIT_FAILURE );
293 valuesReturnFilter= 1 + crit;
295 if ( cvalue == NULL ) {
297 _("missing filter in ValuesReturnFilter control\n"));
298 exit( EXIT_FAILURE );
302 protocol = LDAP_VERSION3;
304 #ifdef LDAP_CONTROL_PAGEDRESULTS
305 } else if ( strcasecmp( control, "pr" ) == 0 ) {
307 /* PagedResults control */
308 if ( pagedResults != 0 ) {
310 _("PagedResultsControl previously specified\n") );
311 exit( EXIT_FAILURE );
314 if( cvalue != NULL ) {
317 promptp = strchr( cvalue, '/' );
318 if ( promptp != NULL ) {
320 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
322 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
326 _("Invalid value for PagedResultsControl,"
327 " %s/%s.\n"), cvalue, promptp );
328 exit( EXIT_FAILURE );
331 num = sscanf( cvalue, "%d", &tmp );
334 _("Invalid value for PagedResultsControl, %s.\n"),
336 exit( EXIT_FAILURE );
339 fprintf( stderr, _("Invalid value for PagedResultsControl.\n"),
341 exit( EXIT_FAILURE );
343 pageSize = (ber_int_t) tmp;
344 pagedResults = 1 + crit;
347 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
348 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
351 _("domainScope control previously specified\n"));
352 exit( EXIT_FAILURE );
354 if( cvalue != NULL ) {
356 _("domainScope: no control value expected\n") );
360 domainScope = 1 + crit;
362 #ifdef LDAP_CONTROL_SUBENTRIES
363 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
366 _("subentries control previously specified\n"));
367 exit( EXIT_FAILURE );
369 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
371 } else if ( strcasecmp( cvalue, "false") == 0 ) {
375 _("subentries control value \"%s\" invalid\n"),
377 exit( EXIT_FAILURE );
379 if( crit ) subentries *= -1;
382 } else if ( strcasecmp( control, "sync" ) == 0 ) {
386 fprintf( stderr, _("sync control previously specified\n") );
387 exit( EXIT_FAILURE );
389 if ( cvalue == NULL ) {
390 fprintf( stderr, _("missing specification of sync control\n"));
391 exit( EXIT_FAILURE );
393 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
394 ldapsync = LDAP_SYNC_REFRESH_ONLY;
395 cookiep = strchr( cvalue, '/' );
396 if ( cookiep != NULL ) {
398 if ( *cookiep != '\0' ) {
399 ber_str2bv( cookiep, 0, 0, &sync_cookie );
402 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
403 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
404 cookiep = strchr( cvalue, '/' );
405 if ( cookiep != NULL ) {
409 slimitp = strchr( cvalue, '/' );
410 if ( slimitp != NULL ) {
413 if ( cookiep != NULL && *cookiep != '\0' )
414 ber_str2bv( cookiep, 0, 0, &sync_cookie );
415 if ( slimitp != NULL && *slimitp != '\0' ) {
416 ival = strtol( slimitp, &next, 10 );
417 if ( next == NULL || next[0] != '\0' ) {
418 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
419 exit( EXIT_FAILURE );
424 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
426 exit( EXIT_FAILURE );
428 if ( crit ) ldapsync *= -1;
431 fprintf( stderr, _("Invalid search extension name: %s\n"),
436 case 'F': /* uri prefix */
437 if( urlpre ) free( urlpre );
438 urlpre = strdup( optarg );
440 case 'l': /* time limit */
441 if ( strcasecmp( optarg, "none" ) == 0 ) {
444 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
445 timelimit = LDAP_MAXINT;
448 ival = strtol( optarg, &next, 10 );
449 if ( next == NULL || next[0] != '\0' ) {
451 _("Unable to parse time limit \"%s\"\n"), optarg );
452 exit( EXIT_FAILURE );
456 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
457 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
459 exit( EXIT_FAILURE );
462 case 'L': /* print entries in LDIF format */
465 case 's': /* search scope */
466 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
467 scope = LDAP_SCOPE_BASE;
468 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
469 scope = LDAP_SCOPE_ONELEVEL;
470 #ifdef LDAP_SCOPE_SUBORDINATE
471 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
472 || ( strcasecmp( optarg, "children" ) == 0 ))
474 scope = LDAP_SCOPE_SUBORDINATE;
476 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
477 scope = LDAP_SCOPE_SUBTREE;
479 fprintf( stderr, _("scope should be base, one, or sub\n") );
483 case 'S': /* sort attribute */
484 sortattr = strdup( optarg );
486 case 't': /* write attribute values to TMPDIR files */
489 case 'T': /* tmpdir */
490 if( tmpdir ) free( tmpdir );
491 tmpdir = strdup( optarg );
493 case 'u': /* include UFN */
496 case 'z': /* size limit */
497 if ( strcasecmp( optarg, "none" ) == 0 ) {
500 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
501 sizelimit = LDAP_MAXINT;
504 ival = strtol( optarg, &next, 10 );
505 if ( next == NULL || next[0] != '\0' ) {
507 _("Unable to parse size limit \"%s\"\n"), optarg );
508 exit( EXIT_FAILURE );
512 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
513 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
515 exit( EXIT_FAILURE );
526 private_conn_setup( LDAP *ld )
529 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
530 != LDAP_OPT_SUCCESS )
532 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
533 exit( EXIT_FAILURE );
536 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
537 != LDAP_OPT_SUCCESS )
540 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
541 exit( EXIT_FAILURE );
544 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
545 != LDAP_OPT_SUCCESS )
548 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
549 exit( EXIT_FAILURE );
555 main( int argc, char **argv )
557 char *filtpattern, **attrs = NULL, line[BUFSIZ];
561 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
563 BerElement *syncber = NULL;
564 struct berval *syncbvalp = NULL;
568 #ifdef LDAP_CONTROL_PAGEDRESULTS
569 npagedresponses = npagedentries = npagedreferences =
570 npagedextended = npagedpartial = 0;
573 prog = lutil_progname( "ldapsearch", argc, argv );
575 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
576 (def_tmpdir = getenv("TMP")) == NULL &&
577 (def_tmpdir = getenv("TEMP")) == NULL )
579 def_tmpdir = LDAP_TMPDIR;
583 def_tmpdir = LDAP_TMPDIR;
585 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
587 if( def_urlpre == NULL ) {
592 sprintf( def_urlpre, "file:///%s/",
593 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
595 urlize( def_urlpre );
597 tool_args( argc, argv );
599 if (( argc - optind < 1 ) ||
600 ( *argv[optind] != '(' /*')'*/ &&
601 ( strchr( argv[optind], '=' ) == NULL ) ) )
603 filtpattern = "(objectclass=*)";
605 filtpattern = strdup( argv[optind++] );
608 if ( argv[optind] != NULL ) {
609 attrs = &argv[optind];
612 if ( infile != NULL ) {
613 if ( infile[0] == '-' && infile[1] == '\0' ) {
615 } else if (( fp = fopen( infile, "r" )) == NULL ) {
621 if ( tmpdir == NULL ) {
624 if ( urlpre == NULL )
628 if( urlpre == NULL ) {
629 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
631 if( urlpre == NULL ) {
636 sprintf( urlpre, "file:///%s/",
637 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
645 ld = tool_conn_setup( 0, &private_conn_setup );
647 if ( pw_file || want_bindpw ) {
649 rc = lutil_get_filed_password( pw_file, &passwd );
650 if( rc ) return EXIT_FAILURE;
652 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
653 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
660 if ( assertion || authzid || manageDSAit || noop
661 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
664 #ifdef LDAP_CONTROL_PAGEDRESULTS
668 || subentries || valuesReturnFilter )
674 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
676 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
677 c[i].ldctl_value.bv_val = NULL;
678 c[i].ldctl_value.bv_len = 0;
679 c[i].ldctl_iscritical = domainScope > 1;
684 #ifdef LDAP_CONTROL_SUBENTRIES
686 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
690 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
692 ber_free( seber, 1 );
693 fprintf( stderr, _("Subentries control encoding error!\n") );
697 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
701 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
702 c[i].ldctl_iscritical = subentries < 1;
708 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
712 if ( sync_cookie.bv_len == 0 ) {
713 err = ber_printf( syncber, "{e}", abs(ldapsync) );
715 err = ber_printf( syncber, "{eO}", abs(ldapsync),
719 if ( err == LBER_ERROR ) {
720 ber_free( syncber, 1 );
721 fprintf( stderr, _("ldap sync control encoding error!\n") );
725 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
729 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
730 c[i].ldctl_value = (*syncbvalp);
731 c[i].ldctl_iscritical = ldapsync < 0;
735 if ( valuesReturnFilter ) {
736 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
740 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
741 ber_free( vrber, 1 );
742 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
746 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
750 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
751 c[i].ldctl_iscritical = valuesReturnFilter > 1;
755 #ifdef LDAP_CONTROL_PAGEDRESULTS
756 if ( pagedResults ) {
757 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
761 ber_printf( prber, "{iO}", pageSize, &page_cookie );
762 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
765 if ( page_cookie.bv_val != NULL ) {
766 ber_memfree( page_cookie.bv_val );
767 page_cookie.bv_val = NULL;
770 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
771 c[i].ldctl_iscritical = pagedResults > 1;
776 tool_server_controls( ld, c, i );
778 #ifdef LDAP_CONTROL_SUBENTRIES
779 ber_free( seber, 1 );
781 ber_free( vrber, 1 );
782 #ifdef LDAP_CONTROL_PAGEDRESULTS
783 ber_free( prber, 1 );
788 fprintf( stderr, _("filter%s: %s\nrequesting: "),
789 infile != NULL ? _(" pattern") : "",
792 if ( attrs == NULL ) {
793 fprintf( stderr, _("ALL") );
795 for ( i = 0; attrs[ i ] != NULL; ++i ) {
796 fprintf( stderr, "%s ", attrs[ i ] );
799 fprintf( stderr, "\n" );
803 printf( _("# extended LDIF\n") );
804 } else if ( ldif < 3 ) {
805 printf( _("version: %d\n\n"), 1 );
810 printf(_("# LDAPv%d\n"), protocol);
811 printf(_("# base <%s> with scope %s\n"),
813 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
814 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
815 #ifdef LDAP_SCOPE_SUBORDINATE
816 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
819 #ifdef LDAP_SCOPE_SUBORDINATE
823 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
825 printf(_("# requesting: "));
827 if ( attrs == NULL ) {
830 for ( i = 0; attrs[ i ] != NULL; ++i ) {
831 printf( "%s ", attrs[ i ] );
836 printf(_("\n# with manageDSAit %scontrol"),
837 manageDSAit > 1 ? _("critical ") : "" );
840 printf(_("\n# with noop %scontrol"),
841 noop > 1 ? _("critical ") : "" );
844 printf(_("\n# with subentries %scontrol: %s"),
845 subentries < 0 ? _("critical ") : "",
846 abs(subentries) == 1 ? "false" : "true" );
848 if ( valuesReturnFilter ) {
849 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
850 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
852 #ifdef LDAP_CONTROL_PAGEDRESULTS
853 if ( pagedResults ) {
854 printf(_("\n# with pagedResults %scontrol: size=%d"),
855 (pagedResults > 1) ? _("critical ") : "",
860 printf( _("\n#\n\n") );
863 if ( infile == NULL ) {
864 rc = dosearch( ld, base, scope, NULL, filtpattern,
865 attrs, attrsonly, NULL, NULL, NULL, -1 );
870 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
871 line[ strlen( line ) - 1 ] = '\0';
877 rc = dosearch( ld, base, scope, filtpattern, line,
878 attrs, attrsonly, NULL, NULL, NULL, -1 );
885 #ifdef LDAP_CONTROL_PAGEDRESULTS
886 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
888 int i, moreEntries, tmpSize;
890 /* Loop to get the next pages when
891 * enter is pressed on the terminal.
893 if ( pagePrompt != 0 ) {
894 if ( entriesLeft > 0 ) {
895 printf( _("Estimate entries: %d\n"), entriesLeft );
897 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
900 moreEntries = getchar();
901 while ( moreEntries != EOF && moreEntries != '\n' ) {
902 if ( i < (int)sizeof(buf) - 1 ) {
903 buf[i] = moreEntries;
906 moreEntries = getchar();
910 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
911 int num = sscanf( buf, "%d", &tmpSize );
913 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
917 pageSize = (ber_int_t)tmpSize;
925 ldap_unbind_ext( ld, NULL, NULL );
926 #ifdef HAVE_CYRUS_SASL
930 ldap_pvt_tls_destroy();
944 LDAPControl **sctrls,
945 LDAPControl **cctrls,
946 struct timeval *timeout,
956 LDAPMessage *res, *msg;
959 struct berval *retdata = NULL;
960 int nresponses_psearch = -1;
961 int cancel_msgid = -1;
963 if( filtpatt != NULL ) {
964 filter = malloc( strlen( filtpatt ) + strlen( value ) );
965 if( filter == NULL ) {
970 sprintf( filter, filtpatt, value );
973 fprintf( stderr, _("filter: %s\n"), filter );
977 printf( _("#\n# filter: %s\n#\n"), filter );
988 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
989 sctrls, cctrls, timeout, sizelimit, &msgid );
991 if ( filtpatt != NULL ) {
995 if( rc != LDAP_SUCCESS ) {
996 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
997 prog, ldap_err2string( rc ), rc );
1001 nresponses = nentries = nreferences = nextended = npartial = 0;
1005 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1006 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1010 (void) ldap_sort_entries( ld, &res,
1011 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1014 for ( msg = ldap_first_message( ld, res );
1016 msg = ldap_next_message( ld, msg ) )
1018 if ( nresponses++ ) putchar('\n');
1019 if ( nresponses_psearch >= 0 )
1020 nresponses_psearch++;
1022 switch( ldap_msgtype( msg ) ) {
1023 case LDAP_RES_SEARCH_ENTRY:
1025 print_entry( ld, msg, attrsonly );
1028 case LDAP_RES_SEARCH_REFERENCE:
1030 print_reference( ld, msg );
1033 case LDAP_RES_EXTENDED:
1035 print_extended( ld, msg );
1037 if( ldap_msgid( msg ) == 0 ) {
1038 /* unsolicited extended operation */
1042 if ( cancel_msgid != -1 &&
1043 cancel_msgid == ldap_msgid( msg ) ) {
1044 printf(_("Cancelled \n"));
1045 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1050 case LDAP_RES_SEARCH_RESULT:
1051 rc = print_result( ld, msg, 1 );
1052 #ifdef LDAP_CONTROL_PAGEDRESULTS
1053 if ( pageSize != 0 ) {
1054 if ( rc == LDAP_SUCCESS ) {
1055 rc = parse_page_control( ld, msg, &page_cookie );
1057 morePagedResults = 0;
1060 morePagedResults = 0;
1064 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1070 case LDAP_RES_INTERMEDIATE:
1072 ldap_parse_intermediate( ld, msg,
1073 &retoid, &retdata, NULL, 0 );
1075 nresponses_psearch = 0;
1077 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1078 printf(_("SyncInfo Received\n"));
1079 ldap_memfree( retoid );
1080 ber_bvfree( retdata );
1084 print_partial( ld, msg );
1085 ldap_memfree( retoid );
1086 ber_bvfree( retdata );
1090 if ( ldapsync && sync_slimit != -1 &&
1091 nresponses_psearch >= sync_slimit ) {
1092 BerElement *msgidber = NULL;
1093 struct berval *msgidvalp = NULL;
1094 msgidber = ber_alloc_t(LBER_USE_DER);
1095 ber_printf(msgidber, "{i}", msgid);
1096 ber_flatten(msgidber, &msgidvalp);
1097 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1098 msgidvalp, NULL, NULL, &cancel_msgid);
1099 nresponses_psearch = -1;
1103 ldap_msgfree( res );
1107 ldap_perror( ld, "ldap_result" );
1112 ldap_msgfree( res );
1113 #ifdef LDAP_CONTROL_PAGEDRESULTS
1114 if ( pagedResults ) {
1115 npagedresponses += nresponses;
1116 npagedentries += nentries;
1117 npagedextended += nextended;
1118 npagedpartial += npartial;
1119 npagedreferences += nreferences;
1120 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1121 printf( _("\n# numResponses: %d\n"), npagedresponses );
1122 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1123 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1124 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1125 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1130 printf( _("\n# numResponses: %d\n"), nresponses );
1131 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1132 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1133 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1134 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1140 /* This is the proposed new way of doing things.
1141 * It is more efficient, but the API is non-standard.
1150 char tmpfname[ 256 ];
1153 BerElement *ber = NULL;
1154 struct berval bv, *bvals, **bvp = &bvals;
1155 LDAPControl **ctrls = NULL;
1158 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1161 ufn = ldap_dn2ufn( bv.bv_val );
1162 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1164 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1166 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1167 if( rc != LDAP_SUCCESS ) {
1168 fprintf(stderr, _("print_entry: %d\n"), rc );
1169 ldap_perror( ld, "ldap_get_entry_controls" );
1170 exit( EXIT_FAILURE );
1174 print_ctrls( ctrls );
1175 ldap_controls_free( ctrls );
1180 ufn = ldap_dn2ufn( bv.bv_val );
1182 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1185 if( ufn != NULL ) ldap_memfree( ufn );
1187 if ( attrsonly ) bvp = NULL;
1189 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1191 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1193 if (bv.bv_val == NULL) break;
1196 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1198 } else if ( bvals ) {
1199 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1200 if ( vals2tmp > 1 || ( vals2tmp &&
1201 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1204 /* write value to file */
1205 snprintf( tmpfname, sizeof tmpfname,
1206 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1207 tmpdir, bv.bv_val );
1210 tmpfd = mkstemp( tmpfname );
1217 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1222 if ( fwrite( bvals[ i ].bv_val,
1223 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1232 snprintf( url, sizeof url, "%s%s", urlpre,
1233 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1236 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1239 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1240 bvals[ i ].bv_val, bvals[ i ].bv_len );
1243 ber_memfree( bvals );
1252 static void print_reference(
1254 LDAPMessage *reference )
1258 LDAPControl **ctrls;
1261 printf(_("# search reference\n"));
1264 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1266 if( rc != LDAP_SUCCESS ) {
1267 ldap_perror(ld, "ldap_parse_reference");
1268 exit( EXIT_FAILURE );
1273 for( i=0; refs[i] != NULL; i++ ) {
1274 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1275 "ref", refs[i], strlen(refs[i]) );
1277 ber_memvfree( (void **) refs );
1281 print_ctrls( ctrls );
1282 ldap_controls_free( ctrls );
1286 static void print_extended(
1288 LDAPMessage *extended )
1291 char *retoid = NULL;
1292 struct berval *retdata = NULL;
1295 printf(_("# extended result response\n"));
1298 rc = ldap_parse_extended_result( ld, extended,
1299 &retoid, &retdata, 0 );
1301 if( rc != LDAP_SUCCESS ) {
1302 ldap_perror(ld, "ldap_parse_extended_result");
1303 exit( EXIT_FAILURE );
1307 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1308 "extended", retoid, retoid ? strlen(retoid) : 0 );
1310 ber_memfree( retoid );
1314 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1315 "data", retdata->bv_val, retdata->bv_len );
1317 ber_bvfree( retdata );
1320 print_result( ld, extended, 0 );
1323 static void print_partial(
1325 LDAPMessage *partial )
1328 char *retoid = NULL;
1329 struct berval *retdata = NULL;
1330 LDAPControl **ctrls = NULL;
1333 printf(_("# extended partial response\n"));
1336 rc = ldap_parse_intermediate( ld, partial,
1337 &retoid, &retdata, &ctrls, 0 );
1339 if( rc != LDAP_SUCCESS ) {
1340 ldap_perror(ld, "ldap_parse_intermediate");
1341 exit( EXIT_FAILURE );
1345 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1346 "partial", retoid, retoid ? strlen(retoid) : 0 );
1349 ber_memfree( retoid );
1353 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1354 "data", retdata->bv_val, retdata->bv_len );
1357 ber_bvfree( retdata );
1361 print_ctrls( ctrls );
1362 ldap_controls_free( ctrls );
1366 static int print_result(
1368 LDAPMessage *result, int search )
1372 char *matcheddn = NULL;
1375 LDAPControl **ctrls = NULL;
1379 printf(_("# search result\n"));
1382 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1386 rc = ldap_parse_result( ld, result,
1387 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1389 if( rc != LDAP_SUCCESS ) {
1390 ldap_perror(ld, "ldap_parse_result");
1391 exit( EXIT_FAILURE );
1396 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1398 } else if ( err != LDAP_SUCCESS ) {
1399 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1405 write_ldif( LDIF_PUT_VALUE,
1406 "matchedDN", matcheddn, strlen(matcheddn) );
1408 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1412 ber_memfree( matcheddn );
1418 write_ldif( LDIF_PUT_TEXT, "text",
1419 text, strlen(text) );
1421 fprintf( stderr, _("Additional information: %s\n"), text );
1425 ber_memfree( text );
1430 for( i=0; refs[i] != NULL; i++ ) {
1432 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1434 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1438 ber_memvfree( (void **) refs );
1442 print_ctrls( ctrls );
1443 ldap_controls_free( ctrls );
1449 static void print_ctrls(
1450 LDAPControl **ctrls )
1453 for(i=0; ctrls[i] != NULL; i++ ) {
1454 /* control: OID criticality base64value */
1455 struct berval *b64 = NULL;
1460 len += strlen( ctrls[i]->ldctl_oid );
1462 /* add enough for space after OID and the critical value itself */
1463 len += ctrls[i]->ldctl_iscritical
1464 ? sizeof("true") : sizeof("false");
1466 /* convert to base64 */
1467 if( ctrls[i]->ldctl_value.bv_len ) {
1468 b64 = ber_memalloc( sizeof(struct berval) );
1470 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1471 ctrls[i]->ldctl_value.bv_len ) + 1;
1472 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1474 b64->bv_len = lutil_b64_ntop(
1475 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1476 ctrls[i]->ldctl_value.bv_len,
1477 b64->bv_val, b64->bv_len );
1481 len += 1 + b64->bv_len;
1484 str = malloc( len + 1 );
1486 strcpy( str, ": " );
1490 strcat( str, ctrls[i]->ldctl_oid );
1491 strcat( str, ctrls[i]->ldctl_iscritical
1492 ? " true" : " false" );
1496 strcat(str, b64->bv_val );
1500 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1501 "control", str, len );
1510 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1514 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1518 fputs( ldif, stdout );
1519 ber_memfree( ldif );
1525 #ifdef LDAP_CONTROL_PAGEDRESULTS
1529 LDAPMessage *result,
1530 struct berval *cookie )
1534 LDAPControl **ctrl = NULL;
1535 LDAPControl *ctrlp = NULL;
1539 rc = ldap_parse_result( ld, result,
1540 &err, NULL, NULL, NULL, &ctrl, 0 );
1542 if( rc != LDAP_SUCCESS ) {
1543 ldap_perror(ld, "ldap_parse_result");
1544 exit( EXIT_FAILURE );
1547 if ( err != LDAP_SUCCESS ) {
1548 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1552 /* Parse the control value
1553 * searchResult ::= SEQUENCE {
1554 * size INTEGER (0..maxInt),
1555 * -- result set size estimate from server - unused
1556 * cookie OCTET STRING
1560 ber = ber_init( &ctrlp->ldctl_value );
1561 if ( ber == NULL ) {
1562 fprintf( stderr, _("Internal error.\n") );
1563 return EXIT_FAILURE;
1566 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1567 (void) ber_free( ber, 1 );
1569 if( tag == LBER_ERROR ) {
1571 _("Paged results response control could not be decoded.\n") );
1572 return EXIT_FAILURE;
1575 if( entriesLeft < 0 ) {
1577 _("Invalid entries estimate in paged results response.\n") );
1578 return EXIT_FAILURE;
1581 if ( cookie->bv_len == 0 ) {
1582 morePagedResults = 0;
1585 ldap_controls_free( ctrl );
1588 morePagedResults = 0;