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 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, or \"none\" or \"max\") 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, *next;
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;
249 _("alias deref should be never, search, find, or always\n") );
253 case 'A': /* retrieve attribute names only -- no values */
256 case 'b': /* search base */
257 base = ber_strdup( optarg );
259 case 'E': /* search extensions */
260 if( protocol == LDAP_VERSION2 ) {
261 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
263 exit( EXIT_FAILURE );
266 /* should be extended to support comma separated list of
267 * [!]key[=value] parameters, e.g. -E !foo,bar=567
272 if( optarg[0] == '!' ) {
277 control = ber_strdup( optarg );
278 if ( (cvalue = strchr( control, '=' )) != NULL ) {
282 if ( strcasecmp( control, "mv" ) == 0 ) {
283 /* ValuesReturnFilter control */
284 if( valuesReturnFilter ) {
286 _("ValuesReturnFilter previously specified\n"));
287 exit( EXIT_FAILURE );
289 valuesReturnFilter= 1 + crit;
291 if ( cvalue == NULL ) {
293 _("missing filter in ValuesReturnFilter control\n"));
294 exit( EXIT_FAILURE );
298 protocol = LDAP_VERSION3;
300 #ifdef LDAP_CONTROL_PAGEDRESULTS
301 } else if ( strcasecmp( control, "pr" ) == 0 ) {
303 /* PagedResults control */
304 if ( pagedResults != 0 ) {
306 _("PagedResultsControl previously specified\n") );
307 exit( EXIT_FAILURE );
310 if( cvalue != NULL ) {
313 promptp = strchr( cvalue, '/' );
314 if ( promptp != NULL ) {
316 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
318 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
322 _("Invalid value for PagedResultsControl,"
323 " %s/%s.\n"), cvalue, promptp );
324 exit( EXIT_FAILURE );
327 num = sscanf( cvalue, "%d", &tmp );
330 _("Invalid value for PagedResultsControl, %s.\n"),
332 exit( EXIT_FAILURE );
335 fprintf( stderr, _("Invalid value for PagedResultsControl.\n"),
337 exit( EXIT_FAILURE );
339 pageSize = (ber_int_t) tmp;
340 pagedResults = 1 + crit;
343 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
344 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
347 _("domainScope control previously specified\n"));
348 exit( EXIT_FAILURE );
350 if( cvalue != NULL ) {
352 _("domainScope: no control value expected\n") );
356 domainScope = 1 + crit;
358 #ifdef LDAP_CONTROL_SUBENTRIES
359 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
362 _("subentries control previously specified\n"));
363 exit( EXIT_FAILURE );
365 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
367 } else if ( strcasecmp( cvalue, "false") == 0 ) {
371 _("subentries control value \"%s\" invalid\n"),
373 exit( EXIT_FAILURE );
375 if( crit ) subentries *= -1;
378 } else if ( strcasecmp( control, "sync" ) == 0 ) {
382 fprintf( stderr, _("sync control previously specified\n") );
383 exit( EXIT_FAILURE );
385 if ( cvalue == NULL ) {
386 fprintf( stderr, _("missing specification of sync control\n"));
387 exit( EXIT_FAILURE );
389 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
390 ldapsync = LDAP_SYNC_REFRESH_ONLY;
391 cookiep = strchr( cvalue, '/' );
392 if ( cookiep != NULL ) {
394 if ( *cookiep != '\0' ) {
395 ber_str2bv( cookiep, 0, 0, &sync_cookie );
398 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
399 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
400 cookiep = strchr( cvalue, '/' );
401 if ( cookiep != NULL ) {
405 slimitp = strchr( cvalue, '/' );
406 if ( slimitp != NULL ) {
409 if ( cookiep != NULL && *cookiep != '\0' )
410 ber_str2bv( cookiep, 0, 0, &sync_cookie );
411 if ( slimitp != NULL && *slimitp != '\0' ) {
412 ival = strtol( slimitp, &next, 10 );
413 if ( next == NULL || next[0] != '\0' ) {
414 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
415 exit( EXIT_FAILURE );
420 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
422 exit( EXIT_FAILURE );
424 if ( crit ) ldapsync *= -1;
427 fprintf( stderr, _("Invalid search extension name: %s\n"),
432 case 'F': /* uri prefix */
433 if( urlpre ) free( urlpre );
434 urlpre = strdup( optarg );
436 case 'l': /* time limit */
437 if ( strcasecmp( optarg, "none" ) == 0 ) {
440 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
441 timelimit = LDAP_MAXINT;
444 ival = strtol( optarg, &next, 10 );
445 if ( next == NULL || next[0] != '\0' ) {
447 _("Unable to parse time limit \"%s\"\n"), optarg );
448 exit( EXIT_FAILURE );
452 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
453 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
455 exit( EXIT_FAILURE );
458 case 'L': /* print entries in LDIF format */
461 case 's': /* search scope */
462 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
463 scope = LDAP_SCOPE_BASE;
464 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
465 scope = LDAP_SCOPE_ONELEVEL;
466 #ifdef LDAP_SCOPE_SUBORDINATE
467 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
468 || ( strcasecmp( optarg, "children" ) == 0 ))
470 scope = LDAP_SCOPE_SUBORDINATE;
472 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
473 scope = LDAP_SCOPE_SUBTREE;
475 fprintf( stderr, _("scope should be base, one, or sub\n") );
479 case 'S': /* sort attribute */
480 sortattr = strdup( optarg );
482 case 't': /* write attribute values to TMPDIR files */
485 case 'T': /* tmpdir */
486 if( tmpdir ) free( tmpdir );
487 tmpdir = strdup( optarg );
489 case 'u': /* include UFN */
492 case 'z': /* size limit */
493 if ( strcasecmp( optarg, "none" ) == 0 ) {
496 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
497 sizelimit = LDAP_MAXINT;
500 ival = strtol( optarg, &next, 10 );
501 if ( next == NULL || next[0] != '\0' ) {
503 _("Unable to parse size limit \"%s\"\n"), optarg );
504 exit( EXIT_FAILURE );
508 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
509 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
511 exit( EXIT_FAILURE );
522 private_conn_setup( LDAP *ld )
525 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
526 != LDAP_OPT_SUCCESS )
528 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
529 exit( EXIT_FAILURE );
532 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
533 != LDAP_OPT_SUCCESS )
536 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
537 exit( EXIT_FAILURE );
540 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
541 != LDAP_OPT_SUCCESS )
544 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
545 exit( EXIT_FAILURE );
551 main( int argc, char **argv )
553 char *filtpattern, **attrs = NULL, line[BUFSIZ];
557 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
559 BerElement *syncber = NULL;
560 struct berval *syncbvalp = NULL;
564 #ifdef LDAP_CONTROL_PAGEDRESULTS
565 npagedresponses = npagedentries = npagedreferences =
566 npagedextended = npagedpartial = 0;
569 prog = lutil_progname( "ldapsearch", argc, argv );
571 lutil_log_initialize(argc, argv);
573 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
574 (def_tmpdir = getenv("TMP")) == NULL &&
575 (def_tmpdir = getenv("TEMP")) == NULL )
577 def_tmpdir = LDAP_TMPDIR;
581 def_tmpdir = LDAP_TMPDIR;
583 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
585 if( def_urlpre == NULL ) {
590 sprintf( def_urlpre, "file:///%s/",
591 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
593 urlize( def_urlpre );
595 tool_args( argc, argv );
597 if (( argc - optind < 1 ) ||
598 ( *argv[optind] != '(' /*')'*/ &&
599 ( strchr( argv[optind], '=' ) == NULL ) ) )
601 filtpattern = "(objectclass=*)";
603 filtpattern = strdup( argv[optind++] );
606 if ( argv[optind] != NULL ) {
607 attrs = &argv[optind];
610 if ( infile != NULL ) {
611 if ( infile[0] == '-' && infile[1] == '\0' ) {
613 } else if (( fp = fopen( infile, "r" )) == NULL ) {
619 if ( tmpdir == NULL ) {
622 if ( urlpre == NULL )
626 if( urlpre == NULL ) {
627 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
629 if( urlpre == NULL ) {
634 sprintf( urlpre, "file:///%s/",
635 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
643 ld = tool_conn_setup( 0, &private_conn_setup );
645 if ( pw_file || want_bindpw ) {
647 rc = lutil_get_filed_password( pw_file, &passwd );
648 if( rc ) return EXIT_FAILURE;
650 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
651 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
658 if ( assertion || authzid || manageDSAit || noop
659 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
662 #ifdef LDAP_CONTROL_PAGEDRESULTS
666 || subentries || valuesReturnFilter )
672 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
674 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
675 c[i].ldctl_value.bv_val = NULL;
676 c[i].ldctl_value.bv_len = 0;
677 c[i].ldctl_iscritical = domainScope > 1;
682 #ifdef LDAP_CONTROL_SUBENTRIES
684 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
688 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
690 ber_free( seber, 1 );
691 fprintf( stderr, _("Subentries control encoding error!\n") );
695 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
699 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
700 c[i].ldctl_iscritical = subentries < 1;
706 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
710 if ( sync_cookie.bv_len == 0 ) {
711 err = ber_printf( syncber, "{e}", abs(ldapsync) );
713 err = ber_printf( syncber, "{eO}", abs(ldapsync),
717 if ( err == LBER_ERROR ) {
718 ber_free( syncber, 1 );
719 fprintf( stderr, _("ldap sync control encoding error!\n") );
723 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
727 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
728 c[i].ldctl_value = (*syncbvalp);
729 c[i].ldctl_iscritical = ldapsync < 0;
733 if ( valuesReturnFilter ) {
734 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
738 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
739 ber_free( vrber, 1 );
740 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
744 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
748 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
749 c[i].ldctl_iscritical = valuesReturnFilter > 1;
753 #ifdef LDAP_CONTROL_PAGEDRESULTS
754 if ( pagedResults ) {
755 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
759 ber_printf( prber, "{iO}", pageSize, &cookie );
760 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
764 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
765 c[i].ldctl_iscritical = pagedResults > 1;
770 tool_server_controls( ld, c, i );
772 #ifdef LDAP_CONTROL_SUBENTRIES
773 ber_free( seber, 1 );
775 ber_free( vrber, 1 );
776 #ifdef LDAP_CONTROL_PAGEDRESULTS
777 ber_free( prber, 1 );
782 fprintf( stderr, _("filter%s: %s\nrequesting: "),
783 infile != NULL ? _(" pattern") : "",
786 if ( attrs == NULL ) {
787 fprintf( stderr, _("ALL") );
789 for ( i = 0; attrs[ i ] != NULL; ++i ) {
790 fprintf( stderr, "%s ", attrs[ i ] );
793 fprintf( stderr, "\n" );
797 printf( _("# extended LDIF\n") );
798 } else if ( ldif < 3 ) {
799 printf( _("version: %d\n\n"), 1 );
804 printf(_("# LDAPv%d\n"), protocol);
805 printf(_("# base <%s> with scope %s\n"),
807 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
808 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
809 #ifdef LDAP_SCOPE_SUBORDINATE
810 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
813 #ifdef LDAP_SCOPE_SUBORDINATE
817 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
819 printf(_("# requesting: "));
821 if ( attrs == NULL ) {
824 for ( i = 0; attrs[ i ] != NULL; ++i ) {
825 printf( "%s ", attrs[ i ] );
830 printf(_("\n# with manageDSAit %scontrol"),
831 manageDSAit > 1 ? _("critical ") : "" );
834 printf(_("\n# with noop %scontrol"),
835 noop > 1 ? _("critical ") : "" );
838 printf(_("\n# with subentries %scontrol: %s"),
839 subentries < 0 ? _("critical ") : "",
840 abs(subentries) == 1 ? "false" : "true" );
842 if ( valuesReturnFilter ) {
843 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
844 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
846 #ifdef LDAP_CONTROL_PAGEDRESULTS
847 if ( pagedResults ) {
848 printf(_("\n# with pagedResults %scontrol: size=%d"),
849 (pagedResults > 1) ? _("critical ") : "",
854 printf( _("\n#\n\n") );
857 if ( infile == NULL ) {
858 rc = dosearch( ld, base, scope, NULL, filtpattern,
859 attrs, attrsonly, NULL, NULL, NULL, -1 );
864 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
865 line[ strlen( line ) - 1 ] = '\0';
871 rc = dosearch( ld, base, scope, filtpattern, line,
872 attrs, attrsonly, NULL, NULL, NULL, -1 );
879 #ifdef LDAP_CONTROL_PAGEDRESULTS
880 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
882 int i, moreEntries, tmpSize;
884 /* Loop to get the next pages when
885 * enter is pressed on the terminal.
887 if ( pagePrompt != 0 ) {
888 if ( entriesLeft > 0 ) {
889 printf( _("Estimate entries: %d\n"), entriesLeft );
891 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
894 moreEntries = getchar();
895 while ( moreEntries != EOF && moreEntries != '\n' ) {
896 if ( i < (int)sizeof(buf) - 1 ) {
897 buf[i] = moreEntries;
900 moreEntries = getchar();
904 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
905 int num = sscanf( buf, "%d", &tmpSize );
907 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
911 pageSize = (ber_int_t)tmpSize;
919 ldap_unbind_ext( ld, NULL, NULL );
920 #ifdef HAVE_CYRUS_SASL
924 ldap_pvt_tls_destroy();
938 LDAPControl **sctrls,
939 LDAPControl **cctrls,
940 struct timeval *timeout,
950 LDAPMessage *res, *msg;
953 struct berval *retdata = NULL;
954 int nresponses_psearch = -1;
955 int cancel_msgid = -1;
957 if( filtpatt != NULL ) {
958 filter = malloc( strlen( filtpatt ) + strlen( value ) );
959 if( filter == NULL ) {
964 sprintf( filter, filtpatt, value );
967 fprintf( stderr, _("filter: %s\n"), filter );
971 printf( _("#\n# filter: %s\n#\n"), filter );
982 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
983 sctrls, cctrls, timeout, sizelimit, &msgid );
985 if ( filtpatt != NULL ) {
989 if( rc != LDAP_SUCCESS ) {
990 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
991 prog, ldap_err2string( rc ), rc );
995 nresponses = nentries = nreferences = nextended = npartial = 0;
999 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1000 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1004 (void) ldap_sort_entries( ld, &res,
1005 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1008 for ( msg = ldap_first_message( ld, res );
1010 msg = ldap_next_message( ld, msg ) )
1012 if ( nresponses++ ) putchar('\n');
1013 if ( nresponses_psearch >= 0 )
1014 nresponses_psearch++;
1016 switch( ldap_msgtype( msg ) ) {
1017 case LDAP_RES_SEARCH_ENTRY:
1019 print_entry( ld, msg, attrsonly );
1022 case LDAP_RES_SEARCH_REFERENCE:
1024 print_reference( ld, msg );
1027 case LDAP_RES_EXTENDED:
1029 print_extended( ld, msg );
1031 if( ldap_msgid( msg ) == 0 ) {
1032 /* unsolicited extended operation */
1036 if ( cancel_msgid != -1 &&
1037 cancel_msgid == ldap_msgid( msg ) ) {
1038 printf(_("Cancelled \n"));
1039 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1044 case LDAP_RES_SEARCH_RESULT:
1045 rc = print_result( ld, msg, 1 );
1046 #ifdef LDAP_CONTROL_PAGEDRESULTS
1047 if ( pageSize != 0 ) {
1048 if ( rc == LDAP_SUCCESS ) {
1049 rc = parse_page_control( ld, msg, &cookie );
1051 morePagedResults = 0;
1054 morePagedResults = 0;
1058 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1064 case LDAP_RES_INTERMEDIATE:
1066 ldap_parse_intermediate( ld, msg,
1067 &retoid, &retdata, NULL, 0 );
1069 nresponses_psearch = 0;
1071 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1072 printf(_("SyncInfo Received\n"));
1073 ldap_memfree( retoid );
1074 ber_bvfree( retdata );
1078 print_partial( ld, msg );
1079 ldap_memfree( retoid );
1080 ber_bvfree( retdata );
1084 if ( ldapsync && sync_slimit != -1 &&
1085 nresponses_psearch >= sync_slimit ) {
1086 BerElement *msgidber = NULL;
1087 struct berval *msgidvalp = NULL;
1088 msgidber = ber_alloc_t(LBER_USE_DER);
1089 ber_printf(msgidber, "{i}", msgid);
1090 ber_flatten(msgidber, &msgidvalp);
1091 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1092 msgidvalp, NULL, NULL, &cancel_msgid);
1093 nresponses_psearch = -1;
1097 ldap_msgfree( res );
1101 ldap_perror( ld, "ldap_result" );
1106 ldap_msgfree( res );
1107 #ifdef LDAP_CONTROL_PAGEDRESULTS
1108 if ( pagedResults ) {
1109 npagedresponses += nresponses;
1110 npagedentries += nentries;
1111 npagedextended += nextended;
1112 npagedpartial += npartial;
1113 npagedreferences += nreferences;
1114 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1115 printf( _("\n# numResponses: %d\n"), npagedresponses );
1116 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1117 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1118 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1119 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1124 printf( _("\n# numResponses: %d\n"), nresponses );
1125 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1126 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1127 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1128 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1134 /* This is the proposed new way of doing things.
1135 * It is more efficient, but the API is non-standard.
1144 char tmpfname[ 256 ];
1147 BerElement *ber = NULL;
1148 struct berval bv, *bvals, **bvp = &bvals;
1149 LDAPControl **ctrls = NULL;
1152 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1155 ufn = ldap_dn2ufn( bv.bv_val );
1156 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1158 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1160 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1161 if( rc != LDAP_SUCCESS ) {
1162 fprintf(stderr, _("print_entry: %d\n"), rc );
1163 ldap_perror( ld, "ldap_get_entry_controls" );
1164 exit( EXIT_FAILURE );
1168 print_ctrls( ctrls );
1169 ldap_controls_free( ctrls );
1174 ufn = ldap_dn2ufn( bv.bv_val );
1176 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1179 if( ufn != NULL ) ldap_memfree( ufn );
1181 if ( attrsonly ) bvp = NULL;
1183 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1185 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1187 if (bv.bv_val == NULL) break;
1190 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1192 } else if ( bvals ) {
1193 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1194 if ( vals2tmp > 1 || ( vals2tmp &&
1195 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1198 /* write value to file */
1199 snprintf( tmpfname, sizeof tmpfname,
1200 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1201 tmpdir, bv.bv_val );
1204 tmpfd = mkstemp( tmpfname );
1211 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1216 if ( fwrite( bvals[ i ].bv_val,
1217 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1226 snprintf( url, sizeof url, "%s%s", urlpre,
1227 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1230 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1233 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1234 bvals[ i ].bv_val, bvals[ i ].bv_len );
1237 ber_memfree( bvals );
1246 static void print_reference(
1248 LDAPMessage *reference )
1252 LDAPControl **ctrls;
1255 printf(_("# search reference\n"));
1258 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1260 if( rc != LDAP_SUCCESS ) {
1261 ldap_perror(ld, "ldap_parse_reference");
1262 exit( EXIT_FAILURE );
1267 for( i=0; refs[i] != NULL; i++ ) {
1268 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1269 "ref", refs[i], strlen(refs[i]) );
1271 ber_memvfree( (void **) refs );
1275 print_ctrls( ctrls );
1276 ldap_controls_free( ctrls );
1280 static void print_extended(
1282 LDAPMessage *extended )
1285 char *retoid = NULL;
1286 struct berval *retdata = NULL;
1289 printf(_("# extended result response\n"));
1292 rc = ldap_parse_extended_result( ld, extended,
1293 &retoid, &retdata, 0 );
1295 if( rc != LDAP_SUCCESS ) {
1296 ldap_perror(ld, "ldap_parse_extended_result");
1297 exit( EXIT_FAILURE );
1301 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1302 "extended", retoid, retoid ? strlen(retoid) : 0 );
1304 ber_memfree( retoid );
1308 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1309 "data", retdata->bv_val, retdata->bv_len );
1311 ber_bvfree( retdata );
1314 print_result( ld, extended, 0 );
1317 static void print_partial(
1319 LDAPMessage *partial )
1322 char *retoid = NULL;
1323 struct berval *retdata = NULL;
1324 LDAPControl **ctrls = NULL;
1327 printf(_("# extended partial response\n"));
1330 rc = ldap_parse_intermediate( ld, partial,
1331 &retoid, &retdata, &ctrls, 0 );
1333 if( rc != LDAP_SUCCESS ) {
1334 ldap_perror(ld, "ldap_parse_intermediate");
1335 exit( EXIT_FAILURE );
1339 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1340 "partial", retoid, retoid ? strlen(retoid) : 0 );
1343 ber_memfree( retoid );
1347 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1348 "data", retdata->bv_val, retdata->bv_len );
1351 ber_bvfree( retdata );
1355 print_ctrls( ctrls );
1356 ldap_controls_free( ctrls );
1360 static int print_result(
1362 LDAPMessage *result, int search )
1366 char *matcheddn = NULL;
1369 LDAPControl **ctrls = NULL;
1373 printf(_("# search result\n"));
1376 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1380 rc = ldap_parse_result( ld, result,
1381 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1383 if( rc != LDAP_SUCCESS ) {
1384 ldap_perror(ld, "ldap_parse_result");
1385 exit( EXIT_FAILURE );
1390 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1392 } else if ( err != LDAP_SUCCESS ) {
1393 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1399 write_ldif( LDIF_PUT_VALUE,
1400 "matchedDN", matcheddn, strlen(matcheddn) );
1402 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1406 ber_memfree( matcheddn );
1412 write_ldif( LDIF_PUT_TEXT, "text",
1413 text, strlen(text) );
1415 fprintf( stderr, _("Additional information: %s\n"), text );
1419 ber_memfree( text );
1424 for( i=0; refs[i] != NULL; i++ ) {
1426 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1428 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1432 ber_memvfree( (void **) refs );
1436 print_ctrls( ctrls );
1437 ldap_controls_free( ctrls );
1443 static void print_ctrls(
1444 LDAPControl **ctrls )
1447 for(i=0; ctrls[i] != NULL; i++ ) {
1448 /* control: OID criticality base64value */
1449 struct berval *b64 = NULL;
1454 len += strlen( ctrls[i]->ldctl_oid );
1456 /* add enough for space after OID and the critical value itself */
1457 len += ctrls[i]->ldctl_iscritical
1458 ? sizeof("true") : sizeof("false");
1460 /* convert to base64 */
1461 if( ctrls[i]->ldctl_value.bv_len ) {
1462 b64 = ber_memalloc( sizeof(struct berval) );
1464 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1465 ctrls[i]->ldctl_value.bv_len ) + 1;
1466 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1468 b64->bv_len = lutil_b64_ntop(
1469 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1470 ctrls[i]->ldctl_value.bv_len,
1471 b64->bv_val, b64->bv_len );
1475 len += 1 + b64->bv_len;
1478 str = malloc( len + 1 );
1480 strcpy( str, ": " );
1484 strcat( str, ctrls[i]->ldctl_oid );
1485 strcat( str, ctrls[i]->ldctl_iscritical
1486 ? " true" : " false" );
1490 strcat(str, b64->bv_val );
1494 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1495 "control", str, len );
1504 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1508 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1512 fputs( ldif, stdout );
1513 ber_memfree( ldif );
1519 #ifdef LDAP_CONTROL_PAGEDRESULTS
1523 LDAPMessage *result,
1524 struct berval *cookie )
1528 LDAPControl **ctrl = NULL;
1529 LDAPControl *ctrlp = NULL;
1532 struct berval servercookie = { 0, NULL };
1534 rc = ldap_parse_result( ld, result,
1535 &err, NULL, NULL, NULL, &ctrl, 0 );
1537 if( rc != LDAP_SUCCESS ) {
1538 ldap_perror(ld, "ldap_parse_result");
1539 exit( EXIT_FAILURE );
1542 if ( err != LDAP_SUCCESS ) {
1543 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1547 /* Parse the control value
1548 * searchResult ::= SEQUENCE {
1549 * size INTEGER (0..maxInt),
1550 * -- result set size estimate from server - unused
1551 * cookie OCTET STRING
1555 ber = ber_init( &ctrlp->ldctl_value );
1556 if ( ber == NULL ) {
1557 fprintf( stderr, _("Internal error.\n") );
1558 return EXIT_FAILURE;
1561 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1562 ber_dupbv( cookie, &servercookie );
1563 (void) ber_free( ber, 1 );
1565 if( tag == LBER_ERROR ) {
1567 _("Paged results response control could not be decoded.\n") );
1568 return EXIT_FAILURE;
1571 if( entriesLeft < 0 ) {
1573 _("Invalid entries estimate in paged results response.\n") );
1574 return EXIT_FAILURE;
1577 if ( servercookie.bv_len == 0 ) {
1578 morePagedResults = 0;
1581 ldap_controls_free( ctrl );
1584 morePagedResults = 0;