1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2005 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>
51 #include <ac/signal.h>
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
67 #include "lutil_ldap.h"
68 #include "ldap_defaults.h"
75 static int scope = LDAP_SCOPE_SUBTREE;
76 static int deref = -1;
78 static int timelimit = -1;
79 static int sizelimit = -1;
81 static char *def_tmpdir;
82 static char *def_urlpre;
84 #if defined(__CYGWIN__) || defined(__MINGW32__)
85 /* Turn off commandline globbing, otherwise you cannot search for
94 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
95 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
96 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
97 fprintf( stderr, _(" which may include:\n"));
98 fprintf( stderr, _(" 1.1 no attributes\n"));
99 fprintf( stderr, _(" * all user attributes\n"));
100 fprintf( stderr, _(" + all operational attributes\n"));
103 fprintf( stderr, _("Search options:\n"));
104 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
105 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
106 fprintf( stderr, _(" -b basedn base dn for search\n"));
107 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
108 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
109 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
111 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
112 #ifdef LDAP_CONTROL_PAGEDRESULTS
113 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
115 #ifdef LDAP_CONTROL_SUBENTRIES
116 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
118 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
119 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
120 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
121 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
122 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
123 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
124 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
125 fprintf( stderr, _(" and version\n"));
126 #ifdef LDAP_SCOPE_SUBORDINATE
127 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
128 #else /* ! LDAP_SCOPE_SUBORDINATE */
129 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
130 #endif /* ! LDAP_SCOPE_SUBORDINATE */
131 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
132 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
133 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
134 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
135 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
136 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
138 exit( EXIT_FAILURE );
141 static void print_entry LDAP_P((
146 static void print_reference(
148 LDAPMessage *reference );
150 static void print_extended(
152 LDAPMessage *extended );
154 static void print_partial(
156 LDAPMessage *partial );
158 static int print_result(
163 static void print_ctrls(
164 LDAPControl **ctrls );
166 static int write_ldif LDAP_P((
172 static int dosearch LDAP_P((
180 LDAPControl **sctrls,
181 LDAPControl **cctrls,
182 struct timeval *timeout,
185 static char *tmpdir = NULL;
186 static char *urlpre = NULL;
187 static char *base = NULL;
188 static char *sortattr = NULL;
189 static int includeufn, vals2tmp = 0, ldif = 0;
191 static int subentries = 0, valuesReturnFilter = 0;
192 static char *vrFilter = NULL;
194 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
195 static int domainScope = 0;
198 static int ldapsync = 0;
199 static struct berval sync_cookie = { 0, NULL };
200 static int sync_slimit = -1;
202 #ifdef LDAP_CONTROL_PAGEDRESULTS
203 static int pagedResults = 0;
204 static int pagePrompt = 1;
205 static ber_int_t pageSize = 0;
206 static ber_int_t entriesLeft = 0;
207 static ber_int_t morePagedResults = 1;
208 static struct berval page_cookie = { 0, NULL };
209 static int npagedresponses;
210 static int npagedentries;
211 static int npagedreferences;
212 static int npagedextended;
213 static int npagedpartial;
215 static int parse_page_control(
218 struct berval *cookie );
226 if (*LDAP_DIRSEP != '/') {
227 for (p = url; *p; p++) {
228 if (*p == *LDAP_DIRSEP)
235 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
236 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
239 handle_private_option( int i )
242 char *control, *cvalue, *next;
244 case 'a': /* set alias deref option */
245 if ( strcasecmp( optarg, "never" ) == 0 ) {
246 deref = LDAP_DEREF_NEVER;
247 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
248 deref = LDAP_DEREF_SEARCHING;
249 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
250 deref = LDAP_DEREF_FINDING;
251 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
252 deref = LDAP_DEREF_ALWAYS;
255 _("alias deref should be never, search, find, or always\n") );
259 case 'A': /* retrieve attribute names only -- no values */
262 case 'b': /* search base */
263 base = ber_strdup( optarg );
265 case 'E': /* search extensions */
266 if( protocol == LDAP_VERSION2 ) {
267 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
269 exit( EXIT_FAILURE );
272 /* should be extended to support comma separated list of
273 * [!]key[=value] parameters, e.g. -E !foo,bar=567
278 if( optarg[0] == '!' ) {
283 control = ber_strdup( optarg );
284 if ( (cvalue = strchr( control, '=' )) != NULL ) {
288 if ( strcasecmp( control, "mv" ) == 0 ) {
289 /* ValuesReturnFilter control */
290 if( valuesReturnFilter ) {
292 _("ValuesReturnFilter previously specified\n"));
293 exit( EXIT_FAILURE );
295 valuesReturnFilter= 1 + crit;
297 if ( cvalue == NULL ) {
299 _("missing filter in ValuesReturnFilter control\n"));
300 exit( EXIT_FAILURE );
304 protocol = LDAP_VERSION3;
306 #ifdef LDAP_CONTROL_PAGEDRESULTS
307 } else if ( strcasecmp( control, "pr" ) == 0 ) {
309 /* PagedResults control */
310 if ( pagedResults != 0 ) {
312 _("PagedResultsControl previously specified\n") );
313 exit( EXIT_FAILURE );
316 if( cvalue != NULL ) {
319 promptp = strchr( cvalue, '/' );
320 if ( promptp != NULL ) {
322 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
324 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
328 _("Invalid value for PagedResultsControl,"
329 " %s/%s.\n"), cvalue, promptp );
330 exit( EXIT_FAILURE );
333 num = sscanf( cvalue, "%d", &tmp );
336 _("Invalid value for PagedResultsControl, %s.\n"),
338 exit( EXIT_FAILURE );
341 fprintf( stderr, _("Invalid value for PagedResultsControl.\n"),
343 exit( EXIT_FAILURE );
345 pageSize = (ber_int_t) tmp;
346 pagedResults = 1 + crit;
349 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
350 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
353 _("domainScope control previously specified\n"));
354 exit( EXIT_FAILURE );
356 if( cvalue != NULL ) {
358 _("domainScope: no control value expected\n") );
362 domainScope = 1 + crit;
365 #ifdef LDAP_CONTROL_SUBENTRIES
366 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
369 _("subentries control previously specified\n"));
370 exit( EXIT_FAILURE );
372 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
374 } else if ( strcasecmp( cvalue, "false") == 0 ) {
378 _("subentries control value \"%s\" invalid\n"),
380 exit( EXIT_FAILURE );
382 if( crit ) subentries *= -1;
385 } else if ( strcasecmp( control, "sync" ) == 0 ) {
389 fprintf( stderr, _("sync control previously specified\n") );
390 exit( EXIT_FAILURE );
392 if ( cvalue == NULL ) {
393 fprintf( stderr, _("missing specification of sync control\n"));
394 exit( EXIT_FAILURE );
396 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
397 ldapsync = LDAP_SYNC_REFRESH_ONLY;
398 cookiep = strchr( cvalue, '/' );
399 if ( cookiep != NULL ) {
401 if ( *cookiep != '\0' ) {
402 ber_str2bv( cookiep, 0, 0, &sync_cookie );
405 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
406 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
407 cookiep = strchr( cvalue, '/' );
408 if ( cookiep != NULL ) {
412 slimitp = strchr( cvalue, '/' );
413 if ( slimitp != NULL ) {
416 if ( cookiep != NULL && *cookiep != '\0' )
417 ber_str2bv( cookiep, 0, 0, &sync_cookie );
418 if ( slimitp != NULL && *slimitp != '\0' ) {
419 ival = strtol( slimitp, &next, 10 );
420 if ( next == NULL || next[0] != '\0' ) {
421 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
422 exit( EXIT_FAILURE );
427 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
429 exit( EXIT_FAILURE );
431 if ( crit ) ldapsync *= -1;
434 fprintf( stderr, _("Invalid search extension name: %s\n"),
439 case 'F': /* uri prefix */
440 if( urlpre ) free( urlpre );
441 urlpre = strdup( optarg );
443 case 'l': /* time limit */
444 if ( strcasecmp( optarg, "none" ) == 0 ) {
447 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
448 timelimit = LDAP_MAXINT;
451 ival = strtol( optarg, &next, 10 );
452 if ( next == NULL || next[0] != '\0' ) {
454 _("Unable to parse time limit \"%s\"\n"), optarg );
455 exit( EXIT_FAILURE );
459 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
460 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
462 exit( EXIT_FAILURE );
465 case 'L': /* print entries in LDIF format */
468 case 's': /* search scope */
469 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
470 scope = LDAP_SCOPE_BASE;
471 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
472 scope = LDAP_SCOPE_ONELEVEL;
473 #ifdef LDAP_SCOPE_SUBORDINATE
474 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
475 || ( strcasecmp( optarg, "children" ) == 0 ))
477 scope = LDAP_SCOPE_SUBORDINATE;
479 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
480 scope = LDAP_SCOPE_SUBTREE;
482 fprintf( stderr, _("scope should be base, one, or sub\n") );
486 case 'S': /* sort attribute */
487 sortattr = strdup( optarg );
489 case 't': /* write attribute values to TMPDIR files */
492 case 'T': /* tmpdir */
493 if( tmpdir ) free( tmpdir );
494 tmpdir = strdup( optarg );
496 case 'u': /* include UFN */
499 case 'z': /* size limit */
500 if ( strcasecmp( optarg, "none" ) == 0 ) {
503 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
504 sizelimit = LDAP_MAXINT;
507 ival = strtol( optarg, &next, 10 );
508 if ( next == NULL || next[0] != '\0' ) {
510 _("Unable to parse size limit \"%s\"\n"), optarg );
511 exit( EXIT_FAILURE );
515 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
516 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
518 exit( EXIT_FAILURE );
529 private_conn_setup( LDAP *ld )
532 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
533 != LDAP_OPT_SUCCESS )
535 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
536 exit( EXIT_FAILURE );
539 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
540 != LDAP_OPT_SUCCESS )
543 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
544 exit( EXIT_FAILURE );
547 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
548 != LDAP_OPT_SUCCESS )
551 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
552 exit( EXIT_FAILURE );
557 main( int argc, char **argv )
559 char *filtpattern, **attrs = NULL, line[BUFSIZ];
563 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
565 BerElement *syncber = NULL;
566 struct berval *syncbvalp = NULL;
570 #ifdef LDAP_CONTROL_PAGEDRESULTS
571 npagedresponses = npagedentries = npagedreferences =
572 npagedextended = npagedpartial = 0;
575 prog = lutil_progname( "ldapsearch", argc, argv );
577 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
578 (def_tmpdir = getenv("TMP")) == NULL &&
579 (def_tmpdir = getenv("TEMP")) == NULL )
581 def_tmpdir = LDAP_TMPDIR;
585 def_tmpdir = LDAP_TMPDIR;
587 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
589 if( def_urlpre == NULL ) {
594 sprintf( def_urlpre, "file:///%s/",
595 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
597 urlize( def_urlpre );
599 tool_args( argc, argv );
601 if (( argc - optind < 1 ) ||
602 ( *argv[optind] != '(' /*')'*/ &&
603 ( strchr( argv[optind], '=' ) == NULL ) ) )
605 filtpattern = "(objectclass=*)";
607 filtpattern = strdup( argv[optind++] );
610 if ( argv[optind] != NULL ) {
611 attrs = &argv[optind];
614 if ( infile != NULL ) {
615 if ( infile[0] == '-' && infile[1] == '\0' ) {
617 } else if (( fp = fopen( infile, "r" )) == NULL ) {
623 if ( tmpdir == NULL ) {
626 if ( urlpre == NULL )
630 if( urlpre == NULL ) {
631 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
633 if( urlpre == NULL ) {
638 sprintf( urlpre, "file:///%s/",
639 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
647 ld = tool_conn_setup( 0, &private_conn_setup );
649 if ( pw_file || want_bindpw ) {
651 rc = lutil_get_filed_password( pw_file, &passwd );
652 if( rc ) return EXIT_FAILURE;
654 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
655 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
662 if ( assertion || authzid || manageDSAit || noop
663 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
666 #ifdef LDAP_CONTROL_PAGEDRESULTS
669 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
671 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
673 || subentries || valuesReturnFilter )
679 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
681 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
682 c[i].ldctl_value.bv_val = NULL;
683 c[i].ldctl_value.bv_len = 0;
684 c[i].ldctl_iscritical = domainScope > 1;
689 #ifdef LDAP_CONTROL_SUBENTRIES
691 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
695 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
697 ber_free( seber, 1 );
698 fprintf( stderr, _("Subentries control encoding error!\n") );
702 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
706 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
707 c[i].ldctl_iscritical = subentries < 1;
713 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
717 if ( sync_cookie.bv_len == 0 ) {
718 err = ber_printf( syncber, "{e}", abs(ldapsync) );
720 err = ber_printf( syncber, "{eO}", abs(ldapsync),
724 if ( err == LBER_ERROR ) {
725 ber_free( syncber, 1 );
726 fprintf( stderr, _("ldap sync control encoding error!\n") );
730 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
734 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
735 c[i].ldctl_value = (*syncbvalp);
736 c[i].ldctl_iscritical = ldapsync < 0;
740 if ( valuesReturnFilter ) {
741 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
745 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
746 ber_free( vrber, 1 );
747 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
751 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
755 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
756 c[i].ldctl_iscritical = valuesReturnFilter > 1;
760 #ifdef LDAP_CONTROL_PAGEDRESULTS
761 if ( pagedResults ) {
762 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
766 ber_printf( prber, "{iO}", pageSize, &page_cookie );
767 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
770 if ( page_cookie.bv_val != NULL ) {
771 ber_memfree( page_cookie.bv_val );
772 page_cookie.bv_val = NULL;
775 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
776 c[i].ldctl_iscritical = pagedResults > 1;
781 tool_server_controls( ld, c, i );
783 #ifdef LDAP_CONTROL_SUBENTRIES
784 ber_free( seber, 1 );
786 ber_free( vrber, 1 );
787 #ifdef LDAP_CONTROL_PAGEDRESULTS
788 ber_free( prber, 1 );
793 fprintf( stderr, _("filter%s: %s\nrequesting: "),
794 infile != NULL ? _(" pattern") : "",
797 if ( attrs == NULL ) {
798 fprintf( stderr, _("ALL") );
800 for ( i = 0; attrs[ i ] != NULL; ++i ) {
801 fprintf( stderr, "%s ", attrs[ i ] );
804 fprintf( stderr, "\n" );
808 printf( _("# extended LDIF\n") );
809 } else if ( ldif < 3 ) {
810 printf( _("version: %d\n\n"), 1 );
815 printf(_("# LDAPv%d\n"), protocol);
816 printf(_("# base <%s> with scope %s\n"),
818 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
819 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
820 #ifdef LDAP_SCOPE_SUBORDINATE
821 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
824 #ifdef LDAP_SCOPE_SUBORDINATE
828 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
830 printf(_("# requesting: "));
832 if ( attrs == NULL ) {
835 for ( i = 0; attrs[ i ] != NULL; ++i ) {
836 printf( "%s ", attrs[ i ] );
841 printf(_("\n# with manageDSAit %scontrol"),
842 manageDSAit > 1 ? _("critical ") : "" );
845 printf(_("\n# with noop %scontrol"),
846 noop > 1 ? _("critical ") : "" );
849 printf(_("\n# with subentries %scontrol: %s"),
850 subentries < 0 ? _("critical ") : "",
851 abs(subentries) == 1 ? "false" : "true" );
853 if ( valuesReturnFilter ) {
854 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
855 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
857 #ifdef LDAP_CONTROL_PAGEDRESULTS
858 if ( pagedResults ) {
859 printf(_("\n# with pagedResults %scontrol: size=%d"),
860 (pagedResults > 1) ? _("critical ") : "",
865 printf( _("\n#\n\n") );
868 if ( infile == NULL ) {
869 rc = dosearch( ld, base, scope, NULL, filtpattern,
870 attrs, attrsonly, NULL, NULL, NULL, -1 );
875 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
876 line[ strlen( line ) - 1 ] = '\0';
882 rc = dosearch( ld, base, scope, filtpattern, line,
883 attrs, attrsonly, NULL, NULL, NULL, -1 );
890 #ifdef LDAP_CONTROL_PAGEDRESULTS
891 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
893 int i, moreEntries, tmpSize;
895 /* Loop to get the next pages when
896 * enter is pressed on the terminal.
898 if ( pagePrompt != 0 ) {
899 if ( entriesLeft > 0 ) {
900 printf( _("Estimate entries: %d\n"), entriesLeft );
902 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
905 moreEntries = getchar();
906 while ( moreEntries != EOF && moreEntries != '\n' ) {
907 if ( i < (int)sizeof(buf) - 1 ) {
908 buf[i] = moreEntries;
911 moreEntries = getchar();
915 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
916 int num = sscanf( buf, "%d", &tmpSize );
918 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
922 pageSize = (ber_int_t)tmpSize;
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,
1009 rc = tool_check_abandon( ld, msgid );
1015 (void) ldap_sort_entries( ld, &res,
1016 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1019 for ( msg = ldap_first_message( ld, res );
1021 msg = ldap_next_message( ld, msg ) )
1023 if ( nresponses++ ) putchar('\n');
1024 if ( nresponses_psearch >= 0 )
1025 nresponses_psearch++;
1027 switch( ldap_msgtype( msg ) ) {
1028 case LDAP_RES_SEARCH_ENTRY:
1030 print_entry( ld, msg, attrsonly );
1033 case LDAP_RES_SEARCH_REFERENCE:
1035 print_reference( ld, msg );
1038 case LDAP_RES_EXTENDED:
1040 print_extended( ld, msg );
1042 if( ldap_msgid( msg ) == 0 ) {
1043 /* unsolicited extended operation */
1047 if ( cancel_msgid != -1 &&
1048 cancel_msgid == ldap_msgid( msg ) ) {
1049 printf(_("Cancelled \n"));
1050 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1055 case LDAP_RES_SEARCH_RESULT:
1056 rc = print_result( ld, msg, 1 );
1057 #ifdef LDAP_CONTROL_PAGEDRESULTS
1058 if ( pageSize != 0 ) {
1059 if ( rc == LDAP_SUCCESS ) {
1060 rc = parse_page_control( ld, msg, &page_cookie );
1062 morePagedResults = 0;
1065 morePagedResults = 0;
1069 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1075 case LDAP_RES_INTERMEDIATE:
1077 ldap_parse_intermediate( ld, msg,
1078 &retoid, &retdata, NULL, 0 );
1080 nresponses_psearch = 0;
1082 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1083 printf(_("SyncInfo Received\n"));
1084 ldap_memfree( retoid );
1085 ber_bvfree( retdata );
1089 print_partial( ld, msg );
1090 ldap_memfree( retoid );
1091 ber_bvfree( retdata );
1095 if ( ldapsync && sync_slimit != -1 &&
1096 nresponses_psearch >= sync_slimit ) {
1097 BerElement *msgidber = NULL;
1098 struct berval *msgidvalp = NULL;
1099 msgidber = ber_alloc_t(LBER_USE_DER);
1100 ber_printf(msgidber, "{i}", msgid);
1101 ber_flatten(msgidber, &msgidvalp);
1102 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1103 msgidvalp, NULL, NULL, &cancel_msgid);
1104 nresponses_psearch = -1;
1108 ldap_msgfree( res );
1113 ldap_perror( ld, "ldap_result" );
1117 ldap_msgfree( res );
1118 #ifdef LDAP_CONTROL_PAGEDRESULTS
1119 if ( pagedResults ) {
1120 npagedresponses += nresponses;
1121 npagedentries += nentries;
1122 npagedextended += nextended;
1123 npagedpartial += npartial;
1124 npagedreferences += nreferences;
1125 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1126 printf( _("\n# numResponses: %d\n"), npagedresponses );
1127 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1128 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1129 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1130 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1135 printf( _("\n# numResponses: %d\n"), nresponses );
1136 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1137 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1138 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1139 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1145 /* This is the proposed new way of doing things.
1146 * It is more efficient, but the API is non-standard.
1155 char tmpfname[ 256 ];
1158 BerElement *ber = NULL;
1159 struct berval bv, *bvals, **bvp = &bvals;
1160 LDAPControl **ctrls = NULL;
1163 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1166 ufn = ldap_dn2ufn( bv.bv_val );
1167 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1169 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1171 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1172 if( rc != LDAP_SUCCESS ) {
1173 fprintf(stderr, _("print_entry: %d\n"), rc );
1174 ldap_perror( ld, "ldap_get_entry_controls" );
1175 exit( EXIT_FAILURE );
1179 print_ctrls( ctrls );
1180 ldap_controls_free( ctrls );
1185 ufn = ldap_dn2ufn( bv.bv_val );
1187 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1190 if( ufn != NULL ) ldap_memfree( ufn );
1192 if ( attrsonly ) bvp = NULL;
1194 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1196 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1198 if (bv.bv_val == NULL) break;
1201 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1203 } else if ( bvals ) {
1204 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1205 if ( vals2tmp > 1 || ( vals2tmp &&
1206 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1209 /* write value to file */
1210 snprintf( tmpfname, sizeof tmpfname,
1211 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1212 tmpdir, bv.bv_val );
1215 tmpfd = mkstemp( tmpfname );
1222 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1227 if ( fwrite( bvals[ i ].bv_val,
1228 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1237 snprintf( url, sizeof url, "%s%s", urlpre,
1238 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1241 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1244 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1245 bvals[ i ].bv_val, bvals[ i ].bv_len );
1248 ber_memfree( bvals );
1257 static void print_reference(
1259 LDAPMessage *reference )
1263 LDAPControl **ctrls;
1266 printf(_("# search reference\n"));
1269 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1271 if( rc != LDAP_SUCCESS ) {
1272 ldap_perror(ld, "ldap_parse_reference");
1273 exit( EXIT_FAILURE );
1278 for( i=0; refs[i] != NULL; i++ ) {
1279 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1280 "ref", refs[i], strlen(refs[i]) );
1282 ber_memvfree( (void **) refs );
1286 print_ctrls( ctrls );
1287 ldap_controls_free( ctrls );
1291 static void print_extended(
1293 LDAPMessage *extended )
1296 char *retoid = NULL;
1297 struct berval *retdata = NULL;
1300 printf(_("# extended result response\n"));
1303 rc = ldap_parse_extended_result( ld, extended,
1304 &retoid, &retdata, 0 );
1306 if( rc != LDAP_SUCCESS ) {
1307 ldap_perror(ld, "ldap_parse_extended_result");
1308 exit( EXIT_FAILURE );
1312 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1313 "extended", retoid, retoid ? strlen(retoid) : 0 );
1315 ber_memfree( retoid );
1319 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1320 "data", retdata->bv_val, retdata->bv_len );
1322 ber_bvfree( retdata );
1325 print_result( ld, extended, 0 );
1328 static void print_partial(
1330 LDAPMessage *partial )
1333 char *retoid = NULL;
1334 struct berval *retdata = NULL;
1335 LDAPControl **ctrls = NULL;
1338 printf(_("# extended partial response\n"));
1341 rc = ldap_parse_intermediate( ld, partial,
1342 &retoid, &retdata, &ctrls, 0 );
1344 if( rc != LDAP_SUCCESS ) {
1345 ldap_perror(ld, "ldap_parse_intermediate");
1346 exit( EXIT_FAILURE );
1350 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1351 "partial", retoid, retoid ? strlen(retoid) : 0 );
1354 ber_memfree( retoid );
1358 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1359 "data", retdata->bv_val, retdata->bv_len );
1362 ber_bvfree( retdata );
1366 print_ctrls( ctrls );
1367 ldap_controls_free( ctrls );
1371 static int print_result(
1373 LDAPMessage *result, int search )
1377 char *matcheddn = NULL;
1380 LDAPControl **ctrls = NULL;
1384 printf(_("# search result\n"));
1387 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1391 rc = ldap_parse_result( ld, result,
1392 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1394 if( rc != LDAP_SUCCESS ) {
1395 ldap_perror(ld, "ldap_parse_result");
1396 exit( EXIT_FAILURE );
1401 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1403 } else if ( err != LDAP_SUCCESS ) {
1404 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1410 write_ldif( LDIF_PUT_VALUE,
1411 "matchedDN", matcheddn, strlen(matcheddn) );
1413 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1417 ber_memfree( matcheddn );
1423 write_ldif( LDIF_PUT_TEXT, "text",
1424 text, strlen(text) );
1426 fprintf( stderr, _("Additional information: %s\n"), text );
1430 ber_memfree( text );
1435 for( i=0; refs[i] != NULL; i++ ) {
1437 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1439 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1443 ber_memvfree( (void **) refs );
1447 print_ctrls( ctrls );
1448 ldap_controls_free( ctrls );
1454 static void print_ctrls(
1455 LDAPControl **ctrls )
1458 for(i=0; ctrls[i] != NULL; i++ ) {
1459 /* control: OID criticality base64value */
1460 struct berval *b64 = NULL;
1465 len += strlen( ctrls[i]->ldctl_oid );
1467 /* add enough for space after OID and the critical value itself */
1468 len += ctrls[i]->ldctl_iscritical
1469 ? sizeof("true") : sizeof("false");
1471 /* convert to base64 */
1472 if( ctrls[i]->ldctl_value.bv_len ) {
1473 b64 = ber_memalloc( sizeof(struct berval) );
1475 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1476 ctrls[i]->ldctl_value.bv_len ) + 1;
1477 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1479 b64->bv_len = lutil_b64_ntop(
1480 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1481 ctrls[i]->ldctl_value.bv_len,
1482 b64->bv_val, b64->bv_len );
1486 len += 1 + b64->bv_len;
1489 str = malloc( len + 1 );
1491 strcpy( str, ": " );
1495 strcat( str, ctrls[i]->ldctl_oid );
1496 strcat( str, ctrls[i]->ldctl_iscritical
1497 ? " true" : " false" );
1501 strcat(str, b64->bv_val );
1505 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1506 "control", str, len );
1515 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1519 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1523 fputs( ldif, stdout );
1524 ber_memfree( ldif );
1530 #ifdef LDAP_CONTROL_PAGEDRESULTS
1534 LDAPMessage *result,
1535 struct berval *cookie )
1539 LDAPControl **ctrl = NULL;
1540 LDAPControl *ctrlp = NULL;
1544 rc = ldap_parse_result( ld, result,
1545 &err, NULL, NULL, NULL, &ctrl, 0 );
1547 if( rc != LDAP_SUCCESS ) {
1548 ldap_perror(ld, "ldap_parse_result");
1549 exit( EXIT_FAILURE );
1552 if ( err != LDAP_SUCCESS ) {
1553 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1557 /* Parse the control value
1558 * searchResult ::= SEQUENCE {
1559 * size INTEGER (0..maxInt),
1560 * -- result set size estimate from server - unused
1561 * cookie OCTET STRING
1565 ber = ber_init( &ctrlp->ldctl_value );
1566 if ( ber == NULL ) {
1567 fprintf( stderr, _("Internal error.\n") );
1568 return EXIT_FAILURE;
1571 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1572 (void) ber_free( ber, 1 );
1574 if( tag == LBER_ERROR ) {
1576 _("Paged results response control could not be decoded.\n") );
1577 return EXIT_FAILURE;
1580 if( entriesLeft < 0 ) {
1582 _("Invalid entries estimate in paged results response.\n") );
1583 return EXIT_FAILURE;
1586 if ( cookie->bv_len == 0 ) {
1587 morePagedResults = 0;
1590 ldap_controls_free( ctrl );
1593 morePagedResults = 0;