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"
76 * NOTE: we use this deprecated function only because
77 * we want ldapsearch to provide some client-side sorting
81 typedef int (LDAP_SORT_AD_CMP_PROC) LDAP_P(( /* deprecated */
82 LDAP_CONST char *left,
83 LDAP_CONST char *right ));
85 LDAP_F( int ) /* deprecated */
86 ldap_sort_entries LDAP_P(( LDAP *ld,
88 LDAP_CONST char *attr,
89 LDAP_SORT_AD_CMP_PROC *cmp ));
92 static int scope = LDAP_SCOPE_SUBTREE;
93 static int deref = -1;
95 static int timelimit = -1;
96 static int sizelimit = -1;
98 static char *def_tmpdir;
99 static char *def_urlpre;
101 #if defined(__CYGWIN__) || defined(__MINGW32__)
102 /* Turn off commandline globbing, otherwise you cannot search for
111 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
112 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
113 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
114 fprintf( stderr, _(" which may include:\n"));
115 fprintf( stderr, _(" 1.1 no attributes\n"));
116 fprintf( stderr, _(" * all user attributes\n"));
117 fprintf( stderr, _(" + all operational attributes\n"));
120 fprintf( stderr, _("Search options:\n"));
121 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
122 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
123 fprintf( stderr, _(" -b basedn base dn for search\n"));
124 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
125 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
126 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
128 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
129 #ifdef LDAP_CONTROL_PAGEDRESULTS
130 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
132 #ifdef LDAP_CONTROL_SUBENTRIES
133 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
135 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
136 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
137 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
138 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
139 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
140 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
141 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
142 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
143 fprintf( stderr, _(" and version\n"));
144 #ifdef LDAP_SCOPE_SUBORDINATE
145 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
146 #else /* ! LDAP_SCOPE_SUBORDINATE */
147 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
148 #endif /* ! LDAP_SCOPE_SUBORDINATE */
149 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
150 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
151 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
152 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
153 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
154 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
156 exit( EXIT_FAILURE );
159 static void print_entry LDAP_P((
164 static void print_reference(
166 LDAPMessage *reference );
168 static void print_extended(
170 LDAPMessage *extended );
172 static void print_partial(
174 LDAPMessage *partial );
176 static int print_result(
181 static int dosearch LDAP_P((
189 LDAPControl **sctrls,
190 LDAPControl **cctrls,
191 struct timeval *timeout,
194 static char *tmpdir = NULL;
195 static char *urlpre = NULL;
196 static char *base = NULL;
197 static char *sortattr = NULL;
198 static int includeufn, vals2tmp = 0;
200 static int subentries = 0, valuesReturnFilter = 0;
201 static char *vrFilter = NULL;
203 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
204 static int domainScope = 0;
207 static int ldapsync = 0;
208 static struct berval sync_cookie = { 0, NULL };
209 static int sync_slimit = -1;
211 #ifdef LDAP_CONTROL_PAGEDRESULTS
212 static int pagedResults = 0;
213 static int pagePrompt = 1;
214 static ber_int_t pageSize = 0;
215 static ber_int_t entriesLeft = 0;
216 static ber_int_t morePagedResults = 1;
217 static struct berval page_cookie = { 0, NULL };
218 static int npagedresponses;
219 static int npagedentries;
220 static int npagedreferences;
221 static int npagedextended;
222 static int npagedpartial;
224 static LDAPControl *c = NULL;
225 static int nctrls = 0;
226 static int save_nctrls = 0;
234 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
235 if ( tmpc == NULL ) {
238 _("unable to make room for control; out of memory?\n"));
247 is_oid( const char *s )
251 if ( !isdigit( s[ 0 ] ) ) {
255 for ( ; s[ 0 ]; s++ ) {
256 if ( s[ 0 ] == '.' ) {
257 if ( s[ 1 ] == '\0' ) {
264 if ( !isdigit( s[ 0 ] ) ) {
268 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
277 static int parse_page_control(
280 struct berval *cookie );
288 if (*LDAP_DIRSEP != '/') {
289 for (p = url; *p; p++) {
290 if (*p == *LDAP_DIRSEP)
297 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
298 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
301 handle_private_option( int i )
304 char *control, *cvalue, *next;
306 case 'a': /* set alias deref option */
307 if ( strcasecmp( optarg, "never" ) == 0 ) {
308 deref = LDAP_DEREF_NEVER;
309 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
310 deref = LDAP_DEREF_SEARCHING;
311 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
312 deref = LDAP_DEREF_FINDING;
313 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
314 deref = LDAP_DEREF_ALWAYS;
317 _("alias deref should be never, search, find, or always\n") );
321 case 'A': /* retrieve attribute names only -- no values */
324 case 'b': /* search base */
325 base = ber_strdup( optarg );
327 case 'E': /* search extensions */
328 if( protocol == LDAP_VERSION2 ) {
329 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
331 exit( EXIT_FAILURE );
334 /* should be extended to support comma separated list of
335 * [!]key[=value] parameters, e.g. -E !foo,bar=567
340 if( optarg[0] == '!' ) {
345 control = ber_strdup( optarg );
346 if ( (cvalue = strchr( control, '=' )) != NULL ) {
350 if ( strcasecmp( control, "mv" ) == 0 ) {
351 /* ValuesReturnFilter control */
352 if( valuesReturnFilter ) {
354 _("ValuesReturnFilter previously specified\n"));
355 exit( EXIT_FAILURE );
357 valuesReturnFilter= 1 + crit;
359 if ( cvalue == NULL ) {
361 _("missing filter in ValuesReturnFilter control\n"));
362 exit( EXIT_FAILURE );
366 protocol = LDAP_VERSION3;
368 #ifdef LDAP_CONTROL_PAGEDRESULTS
369 } else if ( strcasecmp( control, "pr" ) == 0 ) {
371 /* PagedResults control */
372 if ( pagedResults != 0 ) {
374 _("PagedResultsControl previously specified\n") );
375 exit( EXIT_FAILURE );
378 if( cvalue != NULL ) {
381 promptp = strchr( cvalue, '/' );
382 if ( promptp != NULL ) {
384 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
386 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
390 _("Invalid value for PagedResultsControl,"
391 " %s/%s.\n"), cvalue, promptp );
392 exit( EXIT_FAILURE );
395 num = sscanf( cvalue, "%d", &tmp );
398 _("Invalid value for PagedResultsControl, %s.\n"),
400 exit( EXIT_FAILURE );
403 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
404 exit( EXIT_FAILURE );
406 pageSize = (ber_int_t) tmp;
407 pagedResults = 1 + crit;
410 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
411 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
414 _("domainScope control previously specified\n"));
415 exit( EXIT_FAILURE );
417 if( cvalue != NULL ) {
419 _("domainScope: no control value expected\n") );
423 domainScope = 1 + crit;
426 #ifdef LDAP_CONTROL_SUBENTRIES
427 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
430 _("subentries control previously specified\n"));
431 exit( EXIT_FAILURE );
433 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
435 } else if ( strcasecmp( cvalue, "false") == 0 ) {
439 _("subentries control value \"%s\" invalid\n"),
441 exit( EXIT_FAILURE );
443 if( crit ) subentries *= -1;
446 } else if ( strcasecmp( control, "sync" ) == 0 ) {
450 fprintf( stderr, _("sync control previously specified\n") );
451 exit( EXIT_FAILURE );
453 if ( cvalue == NULL ) {
454 fprintf( stderr, _("missing specification of sync control\n"));
455 exit( EXIT_FAILURE );
457 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
458 ldapsync = LDAP_SYNC_REFRESH_ONLY;
459 cookiep = strchr( cvalue, '/' );
460 if ( cookiep != NULL ) {
462 if ( *cookiep != '\0' ) {
463 ber_str2bv( cookiep, 0, 0, &sync_cookie );
466 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
467 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
468 cookiep = strchr( cvalue, '/' );
469 if ( cookiep != NULL ) {
473 slimitp = strchr( cvalue, '/' );
474 if ( slimitp != NULL ) {
477 if ( cookiep != NULL && *cookiep != '\0' )
478 ber_str2bv( cookiep, 0, 0, &sync_cookie );
479 if ( slimitp != NULL && *slimitp != '\0' ) {
480 ival = strtol( slimitp, &next, 10 );
481 if ( next == NULL || next[0] != '\0' ) {
482 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
483 exit( EXIT_FAILURE );
488 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
490 exit( EXIT_FAILURE );
492 if ( crit ) ldapsync *= -1;
494 } else if ( is_oid( control ) ) {
496 exit( EXIT_FAILURE );
500 c[ nctrls - 1 ].ldctl_oid = control;
503 if ( cvalue == NULL ) {
504 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
505 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
507 } else if ( cvalue[ 0 ] == ':' ) {
515 * to use ldif_parse_line2() */
517 ldif_parse_line2( &cvalue[ -2 ], &type,
522 c[ nctrls - 1 ].ldctl_value = value;
525 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
530 c[ nctrls - 1 ].ldctl_iscritical = crit;
533 fprintf( stderr, _("Invalid search extension name: %s\n"),
538 case 'F': /* uri prefix */
539 if( urlpre ) free( urlpre );
540 urlpre = strdup( optarg );
542 case 'l': /* time limit */
543 if ( strcasecmp( optarg, "none" ) == 0 ) {
546 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
547 timelimit = LDAP_MAXINT;
550 ival = strtol( optarg, &next, 10 );
551 if ( next == NULL || next[0] != '\0' ) {
553 _("Unable to parse time limit \"%s\"\n"), optarg );
554 exit( EXIT_FAILURE );
558 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
559 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
561 exit( EXIT_FAILURE );
564 case 'L': /* print entries in LDIF format */
567 case 's': /* search scope */
568 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
569 scope = LDAP_SCOPE_BASE;
570 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
571 scope = LDAP_SCOPE_ONELEVEL;
572 #ifdef LDAP_SCOPE_SUBORDINATE
573 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
574 || ( strcasecmp( optarg, "children" ) == 0 ))
576 scope = LDAP_SCOPE_SUBORDINATE;
578 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
579 scope = LDAP_SCOPE_SUBTREE;
581 fprintf( stderr, _("scope should be base, one, or sub\n") );
585 case 'S': /* sort attribute */
586 sortattr = strdup( optarg );
588 case 't': /* write attribute values to TMPDIR files */
591 case 'T': /* tmpdir */
592 if( tmpdir ) free( tmpdir );
593 tmpdir = strdup( optarg );
595 case 'u': /* include UFN */
598 case 'z': /* size limit */
599 if ( strcasecmp( optarg, "none" ) == 0 ) {
602 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
603 sizelimit = LDAP_MAXINT;
606 ival = strtol( optarg, &next, 10 );
607 if ( next == NULL || next[0] != '\0' ) {
609 _("Unable to parse size limit \"%s\"\n"), optarg );
610 exit( EXIT_FAILURE );
614 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
615 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
617 exit( EXIT_FAILURE );
628 private_conn_setup( LDAP *ld )
631 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
632 != LDAP_OPT_SUCCESS )
634 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
635 exit( EXIT_FAILURE );
638 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
639 != LDAP_OPT_SUCCESS )
642 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
643 exit( EXIT_FAILURE );
646 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
647 != LDAP_OPT_SUCCESS )
650 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
651 exit( EXIT_FAILURE );
656 main( int argc, char **argv )
658 char *filtpattern, **attrs = NULL, line[BUFSIZ];
662 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
664 BerElement *syncber = NULL;
665 struct berval *syncbvalp = NULL;
669 #ifdef LDAP_CONTROL_PAGEDRESULTS
670 npagedresponses = npagedentries = npagedreferences =
671 npagedextended = npagedpartial = 0;
674 prog = lutil_progname( "ldapsearch", argc, argv );
676 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
677 (def_tmpdir = getenv("TMP")) == NULL &&
678 (def_tmpdir = getenv("TEMP")) == NULL )
680 def_tmpdir = LDAP_TMPDIR;
684 def_tmpdir = LDAP_TMPDIR;
686 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
688 if( def_urlpre == NULL ) {
693 sprintf( def_urlpre, "file:///%s/",
694 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
696 urlize( def_urlpre );
698 tool_args( argc, argv );
700 if (( argc - optind < 1 ) ||
701 ( *argv[optind] != '(' /*')'*/ &&
702 ( strchr( argv[optind], '=' ) == NULL ) ) )
704 filtpattern = "(objectclass=*)";
706 filtpattern = argv[optind++];
709 if ( argv[optind] != NULL ) {
710 attrs = &argv[optind];
713 if ( infile != NULL ) {
714 if ( infile[0] == '-' && infile[1] == '\0' ) {
716 } else if (( fp = fopen( infile, "r" )) == NULL ) {
722 if ( tmpdir == NULL ) {
725 if ( urlpre == NULL )
729 if( urlpre == NULL ) {
730 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
732 if( urlpre == NULL ) {
737 sprintf( urlpre, "file:///%s/",
738 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
746 ld = tool_conn_setup( 0, &private_conn_setup );
748 if ( pw_file || want_bindpw ) {
750 rc = lutil_get_filed_password( pw_file, &passwd );
751 if( rc ) return EXIT_FAILURE;
753 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
754 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
761 if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
762 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
765 #ifdef LDAP_CONTROL_PAGEDRESULTS
768 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
770 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
772 || subentries || valuesReturnFilter )
776 save_nctrls = nctrls;
778 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
784 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
785 c[i].ldctl_value.bv_val = NULL;
786 c[i].ldctl_value.bv_len = 0;
787 c[i].ldctl_iscritical = domainScope > 1;
792 #ifdef LDAP_CONTROL_SUBENTRIES
798 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
802 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
804 ber_free( seber, 1 );
805 fprintf( stderr, _("Subentries control encoding error!\n") );
809 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
813 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
814 c[i].ldctl_iscritical = subentries < 1;
824 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
828 if ( sync_cookie.bv_len == 0 ) {
829 err = ber_printf( syncber, "{e}", abs(ldapsync) );
831 err = ber_printf( syncber, "{eO}", abs(ldapsync),
835 if ( err == LBER_ERROR ) {
836 ber_free( syncber, 1 );
837 fprintf( stderr, _("ldap sync control encoding error!\n") );
841 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
845 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
846 c[i].ldctl_value = (*syncbvalp);
847 c[i].ldctl_iscritical = ldapsync < 0;
851 if ( valuesReturnFilter ) {
856 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
860 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
861 ber_free( vrber, 1 );
862 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
866 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
870 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
871 c[i].ldctl_iscritical = valuesReturnFilter > 1;
875 #ifdef LDAP_CONTROL_PAGEDRESULTS
876 if ( pagedResults ) {
881 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
885 ber_printf( prber, "{iO}", pageSize, &page_cookie );
886 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
889 if ( page_cookie.bv_val != NULL ) {
890 ber_memfree( page_cookie.bv_val );
891 page_cookie.bv_val = NULL;
894 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
895 c[i].ldctl_iscritical = pagedResults > 1;
900 tool_server_controls( ld, c, i );
902 /* step back to the original number of controls, so that
903 * those set while parsing args are preserved */
904 nctrls = save_nctrls;
906 #ifdef LDAP_CONTROL_SUBENTRIES
907 ber_free( seber, 1 );
909 ber_free( vrber, 1 );
910 #ifdef LDAP_CONTROL_PAGEDRESULTS
911 ber_free( prber, 1 );
916 fprintf( stderr, _("filter%s: %s\nrequesting: "),
917 infile != NULL ? _(" pattern") : "",
920 if ( attrs == NULL ) {
921 fprintf( stderr, _("All userApplication attributes") );
923 for ( i = 0; attrs[ i ] != NULL; ++i ) {
924 fprintf( stderr, "%s ", attrs[ i ] );
927 fprintf( stderr, "\n" );
931 printf( _("# extended LDIF\n") );
932 } else if ( ldif < 3 ) {
933 printf( _("version: %d\n\n"), 1 );
938 printf(_("# LDAPv%d\n"), protocol);
939 printf(_("# base <%s> with scope %s\n"),
941 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
942 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
943 #ifdef LDAP_SCOPE_SUBORDINATE
944 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
947 #ifdef LDAP_SCOPE_SUBORDINATE
951 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
953 printf(_("# requesting: "));
955 if ( attrs == NULL ) {
958 for ( i = 0; attrs[ i ] != NULL; ++i ) {
959 printf( "%s ", attrs[ i ] );
964 printf(_("\n# with manageDSAit %scontrol"),
965 manageDSAit > 1 ? _("critical ") : "" );
968 printf(_("\n# with noop %scontrol"),
969 noop > 1 ? _("critical ") : "" );
972 printf(_("\n# with subentries %scontrol: %s"),
973 subentries < 0 ? _("critical ") : "",
974 abs(subentries) == 1 ? "false" : "true" );
976 if ( valuesReturnFilter ) {
977 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
978 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
980 #ifdef LDAP_CONTROL_PAGEDRESULTS
981 if ( pagedResults ) {
982 printf(_("\n# with pagedResults %scontrol: size=%d"),
983 (pagedResults > 1) ? _("critical ") : "",
988 printf( _("\n#\n\n") );
991 if ( infile == NULL ) {
992 rc = dosearch( ld, base, scope, NULL, filtpattern,
993 attrs, attrsonly, NULL, NULL, NULL, -1 );
998 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
999 line[ strlen( line ) - 1 ] = '\0';
1005 rc = dosearch( ld, base, scope, filtpattern, line,
1006 attrs, attrsonly, NULL, NULL, NULL, -1 );
1008 if ( fp != stdin ) {
1013 #ifdef LDAP_CONTROL_PAGEDRESULTS
1014 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
1016 int i, moreEntries, tmpSize;
1018 /* Loop to get the next pages when
1019 * enter is pressed on the terminal.
1021 if ( pagePrompt != 0 ) {
1022 if ( entriesLeft > 0 ) {
1023 printf( _("Estimate entries: %d\n"), entriesLeft );
1025 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1028 moreEntries = getchar();
1029 while ( moreEntries != EOF && moreEntries != '\n' ) {
1030 if ( i < (int)sizeof(buf) - 1 ) {
1031 buf[i] = moreEntries;
1034 moreEntries = getchar();
1038 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1039 int num = sscanf( buf, "%d", &tmpSize );
1041 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
1042 return EXIT_FAILURE;
1045 pageSize = (ber_int_t)tmpSize;
1057 for ( ; save_nctrls-- > 0; ) {
1058 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1068 static int dosearch(
1076 LDAPControl **sctrls,
1077 LDAPControl **cctrls,
1078 struct timeval *timeout,
1088 LDAPMessage *res, *msg;
1090 char *retoid = NULL;
1091 struct berval *retdata = NULL;
1092 int nresponses_psearch = -1;
1093 int cancel_msgid = -1;
1095 if( filtpatt != NULL ) {
1096 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1097 if( filter == NULL ) {
1099 return EXIT_FAILURE;
1102 sprintf( filter, filtpatt, value );
1105 fprintf( stderr, _("filter: %s\n"), filter );
1109 printf( _("#\n# filter: %s\n#\n"), filter );
1117 return LDAP_SUCCESS;
1120 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1121 sctrls, cctrls, timeout, sizelimit, &msgid );
1123 if ( filtpatt != NULL ) {
1127 if( rc != LDAP_SUCCESS ) {
1128 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1129 prog, ldap_err2string( rc ), rc );
1133 nresponses = nentries = nreferences = nextended = npartial = 0;
1137 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1138 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1141 rc = tool_check_abandon( ld, msgid );
1147 (void) ldap_sort_entries( ld, &res,
1148 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1151 for ( msg = ldap_first_message( ld, res );
1153 msg = ldap_next_message( ld, msg ) )
1155 if ( nresponses++ ) putchar('\n');
1156 if ( nresponses_psearch >= 0 )
1157 nresponses_psearch++;
1159 switch( ldap_msgtype( msg ) ) {
1160 case LDAP_RES_SEARCH_ENTRY:
1162 print_entry( ld, msg, attrsonly );
1165 case LDAP_RES_SEARCH_REFERENCE:
1167 print_reference( ld, msg );
1170 case LDAP_RES_EXTENDED:
1172 print_extended( ld, msg );
1174 if( ldap_msgid( msg ) == 0 ) {
1175 /* unsolicited extended operation */
1179 if ( cancel_msgid != -1 &&
1180 cancel_msgid == ldap_msgid( msg ) ) {
1181 printf(_("Cancelled \n"));
1182 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1187 case LDAP_RES_SEARCH_RESULT:
1188 rc = print_result( ld, msg, 1 );
1189 #ifdef LDAP_CONTROL_PAGEDRESULTS
1190 if ( pageSize != 0 ) {
1191 if ( rc == LDAP_SUCCESS ) {
1192 rc = parse_page_control( ld, msg, &page_cookie );
1194 morePagedResults = 0;
1197 morePagedResults = 0;
1201 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1207 case LDAP_RES_INTERMEDIATE:
1209 ldap_parse_intermediate( ld, msg,
1210 &retoid, &retdata, NULL, 0 );
1212 nresponses_psearch = 0;
1214 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1215 printf(_("SyncInfo Received\n"));
1216 ldap_memfree( retoid );
1217 ber_bvfree( retdata );
1221 print_partial( ld, msg );
1222 ldap_memfree( retoid );
1223 ber_bvfree( retdata );
1227 if ( ldapsync && sync_slimit != -1 &&
1228 nresponses_psearch >= sync_slimit ) {
1229 BerElement *msgidber = NULL;
1230 struct berval *msgidvalp = NULL;
1231 msgidber = ber_alloc_t(LBER_USE_DER);
1232 ber_printf(msgidber, "{i}", msgid);
1233 ber_flatten(msgidber, &msgidvalp);
1234 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1235 msgidvalp, NULL, NULL, &cancel_msgid);
1236 nresponses_psearch = -1;
1240 ldap_msgfree( res );
1245 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1249 ldap_msgfree( res );
1250 #ifdef LDAP_CONTROL_PAGEDRESULTS
1251 if ( pagedResults ) {
1252 npagedresponses += nresponses;
1253 npagedentries += nentries;
1254 npagedextended += nextended;
1255 npagedpartial += npartial;
1256 npagedreferences += nreferences;
1257 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1258 printf( _("\n# numResponses: %d\n"), npagedresponses );
1259 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1260 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1261 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1262 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1267 printf( _("\n# numResponses: %d\n"), nresponses );
1268 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1269 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1270 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1271 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1277 /* This is the proposed new way of doing things.
1278 * It is more efficient, but the API is non-standard.
1287 char tmpfname[ 256 ];
1290 BerElement *ber = NULL;
1291 struct berval bv, *bvals, **bvp = &bvals;
1292 LDAPControl **ctrls = NULL;
1295 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1298 ufn = ldap_dn2ufn( bv.bv_val );
1299 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1301 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1303 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1304 if( rc != LDAP_SUCCESS ) {
1305 fprintf(stderr, _("print_entry: %d\n"), rc );
1306 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1307 exit( EXIT_FAILURE );
1311 tool_print_ctrls( ld, ctrls );
1312 ldap_controls_free( ctrls );
1317 ufn = ldap_dn2ufn( bv.bv_val );
1319 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1322 if( ufn != NULL ) ldap_memfree( ufn );
1324 if ( attrsonly ) bvp = NULL;
1326 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1328 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1330 if (bv.bv_val == NULL) break;
1333 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1335 } else if ( bvals ) {
1336 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1337 if ( vals2tmp > 1 || ( vals2tmp &&
1338 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1341 /* write value to file */
1342 snprintf( tmpfname, sizeof tmpfname,
1343 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1344 tmpdir, bv.bv_val );
1347 tmpfd = mkstemp( tmpfname );
1354 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1359 if ( fwrite( bvals[ i ].bv_val,
1360 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1369 snprintf( url, sizeof url, "%s%s", urlpre,
1370 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1373 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1376 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1377 bvals[ i ].bv_val, bvals[ i ].bv_len );
1380 ber_memfree( bvals );
1389 static void print_reference(
1391 LDAPMessage *reference )
1395 LDAPControl **ctrls;
1398 printf(_("# search reference\n"));
1401 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1403 if( rc != LDAP_SUCCESS ) {
1404 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1405 exit( EXIT_FAILURE );
1410 for( i=0; refs[i] != NULL; i++ ) {
1411 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1412 "ref", refs[i], strlen(refs[i]) );
1414 ber_memvfree( (void **) refs );
1418 tool_print_ctrls( ld, ctrls );
1419 ldap_controls_free( ctrls );
1423 static void print_extended(
1425 LDAPMessage *extended )
1428 char *retoid = NULL;
1429 struct berval *retdata = NULL;
1432 printf(_("# extended result response\n"));
1435 rc = ldap_parse_extended_result( ld, extended,
1436 &retoid, &retdata, 0 );
1438 if( rc != LDAP_SUCCESS ) {
1439 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1440 exit( EXIT_FAILURE );
1444 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1445 "extended", retoid, retoid ? strlen(retoid) : 0 );
1447 ber_memfree( retoid );
1451 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1452 "data", retdata->bv_val, retdata->bv_len );
1454 ber_bvfree( retdata );
1457 print_result( ld, extended, 0 );
1460 static void print_partial(
1462 LDAPMessage *partial )
1465 char *retoid = NULL;
1466 struct berval *retdata = NULL;
1467 LDAPControl **ctrls = NULL;
1470 printf(_("# extended partial response\n"));
1473 rc = ldap_parse_intermediate( ld, partial,
1474 &retoid, &retdata, &ctrls, 0 );
1476 if( rc != LDAP_SUCCESS ) {
1477 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1478 exit( EXIT_FAILURE );
1482 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1483 "partial", retoid, retoid ? strlen(retoid) : 0 );
1486 ber_memfree( retoid );
1490 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1491 "data", retdata->bv_val, retdata->bv_len );
1494 ber_bvfree( retdata );
1498 tool_print_ctrls( ld, ctrls );
1499 ldap_controls_free( ctrls );
1503 static int print_result(
1505 LDAPMessage *result, int search )
1509 char *matcheddn = NULL;
1512 LDAPControl **ctrls = NULL;
1516 printf(_("# search result\n"));
1519 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1523 rc = ldap_parse_result( ld, result,
1524 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1526 if( rc != LDAP_SUCCESS ) {
1527 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1528 exit( EXIT_FAILURE );
1533 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1535 } else if ( err != LDAP_SUCCESS ) {
1536 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1542 tool_write_ldif( LDIF_PUT_VALUE,
1543 "matchedDN", matcheddn, strlen(matcheddn) );
1545 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1549 ber_memfree( matcheddn );
1555 tool_write_ldif( LDIF_PUT_TEXT, "text",
1556 text, strlen(text) );
1558 fprintf( stderr, _("Additional information: %s\n"), text );
1562 ber_memfree( text );
1567 for( i=0; refs[i] != NULL; i++ ) {
1569 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1571 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1575 ber_memvfree( (void **) refs );
1579 tool_print_ctrls( ld, ctrls );
1580 ldap_controls_free( ctrls );
1586 #ifdef LDAP_CONTROL_PAGEDRESULTS
1590 LDAPMessage *result,
1591 struct berval *cookie )
1595 LDAPControl **ctrl = NULL;
1596 LDAPControl *ctrlp = NULL;
1600 rc = ldap_parse_result( ld, result,
1601 &err, NULL, NULL, NULL, &ctrl, 0 );
1603 if( rc != LDAP_SUCCESS ) {
1604 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1605 exit( EXIT_FAILURE );
1608 if ( err != LDAP_SUCCESS ) {
1609 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1613 /* Parse the control value
1614 * searchResult ::= SEQUENCE {
1615 * size INTEGER (0..maxInt),
1616 * -- result set size estimate from server - unused
1617 * cookie OCTET STRING
1621 ber = ber_init( &ctrlp->ldctl_value );
1622 if ( ber == NULL ) {
1623 fprintf( stderr, _("Internal error.\n") );
1624 return EXIT_FAILURE;
1627 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1628 (void) ber_free( ber, 1 );
1630 if( tag == LBER_ERROR ) {
1632 _("Paged results response control could not be decoded.\n") );
1633 return EXIT_FAILURE;
1636 if( entriesLeft < 0 ) {
1638 _("Invalid entries estimate in paged results response.\n") );
1639 return EXIT_FAILURE;
1642 if ( cookie->bv_len == 0 ) {
1643 morePagedResults = 0;
1646 ldap_controls_free( ctrl );
1649 morePagedResults = 0;