1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2008 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;
100 static char *def_tmpdir;
101 static char *def_urlpre;
103 #if defined(__CYGWIN__) || defined(__MINGW32__)
104 /* Turn off commandline globbing, otherwise you cannot search for
113 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
114 fprintf( stderr, _(" filter\tRFC 4515 compliant LDAP search filter\n"));
115 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
116 fprintf( stderr, _(" which may include:\n"));
117 fprintf( stderr, _(" 1.1 no attributes\n"));
118 fprintf( stderr, _(" * all user attributes\n"));
119 fprintf( stderr, _(" + all operational attributes\n"));
122 fprintf( stderr, _("Search options:\n"));
123 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
124 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
125 fprintf( stderr, _(" -b basedn base dn for search\n"));
126 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
127 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
128 fprintf( stderr, _(" !dontUseCopy (Don't Use Copy)\n"));
129 fprintf( stderr, _(" [!]mv=<filter> (RFC 3876 matched values filter)\n"));
130 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (RFC 2696 paged results/prompt)\n"));
131 fprintf( stderr, _(" [!]sss=[-]<attr[:OID]>[/[-]<attr[:OID]>...]\n"));
132 fprintf( stderr, _(" (RFC 2891 server side sorting)\n"));
133 fprintf( stderr, _(" [!]subentries[=true|false] (RFC 3672 subentries)\n"));
134 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (RFC 4533 LDAP Sync refreshOnly)\n"));
135 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (refreshAndPersist)\n"));
136 #ifdef LDAP_CONTROL_X_DEREF
137 fprintf( stderr, _(" [!]deref=derefAttr:attr[,...][;derefAttr:attr[,...][;...]]\n"));
139 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
140 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
141 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
142 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
143 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
144 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
145 fprintf( stderr, _(" and version\n"));
146 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
147 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
148 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
149 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
150 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
151 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
152 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
154 exit( EXIT_FAILURE );
157 static void print_entry LDAP_P((
162 static void print_reference(
164 LDAPMessage *reference );
166 static void print_extended(
168 LDAPMessage *extended );
170 static void print_partial(
172 LDAPMessage *partial );
174 static int print_result(
179 static int dosearch LDAP_P((
187 LDAPControl **sctrls,
188 LDAPControl **cctrls,
189 struct timeval *timeout,
192 static char *tmpdir = NULL;
193 static char *urlpre = NULL;
194 static char *base = NULL;
195 static char *sortattr = NULL;
196 static int includeufn, vals2tmp = 0;
198 static int subentries = 0, valuesReturnFilter = 0;
199 static char *vrFilter = NULL;
201 #ifdef LDAP_CONTROL_DONTUSECOPY
202 static int dontUseCopy = 0;
205 static int domainScope = 0;
208 static LDAPSortKey **sss_keys = NULL;
210 static int ldapsync = 0;
211 static struct berval sync_cookie = { 0, NULL };
212 static int sync_slimit = -1;
214 /* cookie and morePagedResults moved to common.c */
215 static int pagedResults = 0;
216 static int pagePrompt = 1;
217 static ber_int_t pageSize = 0;
218 static ber_int_t entriesLeft = 0;
219 static int npagedresponses;
220 static int npagedentries;
221 static int npagedreferences;
222 static int npagedextended;
223 static int npagedpartial;
225 static LDAPControl *c = NULL;
226 static int nctrls = 0;
227 static int save_nctrls = 0;
229 #ifdef LDAP_CONTROL_X_DEREF
230 static int derefcrit;
231 static LDAPDerefSpec *ds;
232 static struct berval derefval;
241 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
242 if ( tmpc == NULL ) {
245 _("unable to make room for control; out of memory?\n"));
258 if (*LDAP_DIRSEP != '/') {
259 for (p = url; *p; p++) {
260 if (*p == *LDAP_DIRSEP)
267 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
268 "Cd:D:e:f:h:H:IMnNO:o:p:P:QR:U:vVw:WxX:y:Y:Z";
271 handle_private_option( int i )
276 case 'a': /* set alias deref option */
277 if ( strcasecmp( optarg, "never" ) == 0 ) {
278 deref = LDAP_DEREF_NEVER;
279 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
280 deref = LDAP_DEREF_SEARCHING;
281 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
282 deref = LDAP_DEREF_FINDING;
283 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
284 deref = LDAP_DEREF_ALWAYS;
287 _("alias deref should be never, search, find, or always\n") );
291 case 'A': /* retrieve attribute names only -- no values */
294 case 'b': /* search base */
295 base = ber_strdup( optarg );
297 case 'E': /* search extensions */
298 if( protocol == LDAP_VERSION2 ) {
299 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
301 exit( EXIT_FAILURE );
304 /* should be extended to support comma separated list of
305 * [!]key[=value] parameters, e.g. -E !foo,bar=567
310 while ( optarg[0] == '!' ) {
315 control = ber_strdup( optarg );
316 if ( (cvalue = strchr( control, '=' )) != NULL ) {
320 if ( strcasecmp( control, "mv" ) == 0 ) {
321 /* ValuesReturnFilter control */
322 if( valuesReturnFilter ) {
324 _("ValuesReturnFilter previously specified\n"));
325 exit( EXIT_FAILURE );
327 valuesReturnFilter= 1 + crit;
329 if ( cvalue == NULL ) {
331 _("missing filter in ValuesReturnFilter control\n"));
332 exit( EXIT_FAILURE );
336 protocol = LDAP_VERSION3;
338 } else if ( strcasecmp( control, "pr" ) == 0 ) {
340 /* PagedResults control */
341 if ( pagedResults != 0 ) {
343 _("PagedResultsControl previously specified\n") );
344 exit( EXIT_FAILURE );
347 if( cvalue != NULL ) {
350 promptp = strchr( cvalue, '/' );
351 if ( promptp != NULL ) {
353 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
355 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
359 _("Invalid value for PagedResultsControl,"
360 " %s/%s.\n"), cvalue, promptp );
361 exit( EXIT_FAILURE );
364 num = sscanf( cvalue, "%d", &tmp );
367 _("Invalid value for PagedResultsControl, %s.\n"),
369 exit( EXIT_FAILURE );
372 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
373 exit( EXIT_FAILURE );
375 pageSize = (ber_int_t) tmp;
376 pagedResults = 1 + crit;
378 #ifdef LDAP_CONTROL_DONTUSECOPY
379 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
382 _("dontUseCopy control previously specified\n"));
383 exit( EXIT_FAILURE );
385 if( cvalue != NULL ) {
387 _("dontUseCopy: no control value expected\n") );
392 _("dontUseCopy: critical flag required\n") );
396 dontUseCopy = 1 + crit;
398 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
401 _("domainScope control previously specified\n"));
402 exit( EXIT_FAILURE );
404 if( cvalue != NULL ) {
406 _("domainScope: no control value expected\n") );
410 domainScope = 1 + crit;
412 } else if ( strcasecmp( control, "sss" ) == 0 ) {
416 _("server side sorting control previously specified\n"));
417 exit( EXIT_FAILURE );
419 if( cvalue == NULL ) {
421 _("missing specification of sss control\n") );
422 exit( EXIT_FAILURE );
425 while ( ( keyp = strchr(keyp, '/') ) != NULL ) {
428 if ( ldap_create_sort_keylist( &sss_keys, cvalue )) {
430 _("server side sorting control value \"%s\" invalid\n"),
432 exit( EXIT_FAILURE );
437 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
440 _("subentries control previously specified\n"));
441 exit( EXIT_FAILURE );
443 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
445 } else if ( strcasecmp( cvalue, "false") == 0 ) {
449 _("subentries control value \"%s\" invalid\n"),
451 exit( EXIT_FAILURE );
453 if( crit ) subentries *= -1;
455 } else if ( strcasecmp( control, "sync" ) == 0 ) {
459 fprintf( stderr, _("sync control previously specified\n") );
460 exit( EXIT_FAILURE );
462 if ( cvalue == NULL ) {
463 fprintf( stderr, _("missing specification of sync control\n"));
464 exit( EXIT_FAILURE );
466 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
467 ldapsync = LDAP_SYNC_REFRESH_ONLY;
468 cookiep = strchr( cvalue, '/' );
469 if ( cookiep != NULL ) {
471 if ( *cookiep != '\0' ) {
472 ber_str2bv( cookiep, 0, 0, &sync_cookie );
475 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
476 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
477 cookiep = strchr( cvalue, '/' );
478 if ( cookiep != NULL ) {
482 slimitp = strchr( cvalue, '/' );
483 if ( slimitp != NULL ) {
486 if ( cookiep != NULL && *cookiep != '\0' )
487 ber_str2bv( cookiep, 0, 0, &sync_cookie );
488 if ( slimitp != NULL && *slimitp != '\0' ) {
489 ival = strtol( slimitp, &next, 10 );
490 if ( next == NULL || next[0] != '\0' ) {
491 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
492 exit( EXIT_FAILURE );
497 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
499 exit( EXIT_FAILURE );
501 if ( crit ) ldapsync *= -1;
503 #ifdef LDAP_CONTROL_X_DEREF
504 } else if ( strcasecmp( control, "deref" ) == 0 ) {
508 /* cvalue is something like
510 * derefAttr:attr[,attr[...]][;derefAttr:attr[,attr[...]]]"
513 specs = ldap_str2charray( cvalue, ";" );
514 if ( specs == NULL ) {
515 fprintf( stderr, _("deref specs \"%s\" invalid\n"),
517 exit( EXIT_FAILURE );
519 for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ )
522 ds = ldap_memcalloc( ispecs + 1, sizeof( LDAPDerefSpec ) );
525 exit( EXIT_FAILURE );
528 for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ ) {
531 ptr = strchr( specs[ ispecs ], ':' );
533 fprintf( stderr, _("deref specs \"%s\" invalid\n"),
535 exit( EXIT_FAILURE );
538 ds[ ispecs ].derefAttr = specs[ ispecs ];
540 ds[ ispecs ].attributes = ldap_str2charray( ptr, "," );
543 derefcrit = 1 + crit;
545 ldap_memfree( specs );
546 #endif /* LDAP_CONTROL_X_DEREF */
548 } else if ( tool_is_oid( control ) ) {
551 for ( i = 0; c[ i ].ldctl_oid != NULL; i++ ) {
552 if ( strcmp( control, c[ i ].ldctl_oid ) == 0 ) {
553 fprintf( stderr, "%s control previously specified\n", control );
554 exit( EXIT_FAILURE );
560 exit( EXIT_FAILURE );
564 c[ nctrls - 1 ].ldctl_oid = control;
567 if ( cvalue == NULL ) {
568 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
569 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
571 } else if ( cvalue[ 0 ] == ':' ) {
579 * to use ldif_parse_line2() */
581 ldif_parse_line2( &cvalue[ -2 ], &type,
586 c[ nctrls - 1 ].ldctl_value = value;
589 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
594 c[ nctrls - 1 ].ldctl_iscritical = crit;
597 fprintf( stderr, _("Invalid search extension name: %s\n"),
602 case 'F': /* uri prefix */
603 if( urlpre ) free( urlpre );
604 urlpre = strdup( optarg );
606 case 'l': /* time limit */
607 if ( strcasecmp( optarg, "none" ) == 0 ) {
610 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
611 timelimit = LDAP_MAXINT;
614 ival = strtol( optarg, &next, 10 );
615 if ( next == NULL || next[0] != '\0' ) {
617 _("Unable to parse time limit \"%s\"\n"), optarg );
618 exit( EXIT_FAILURE );
622 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
623 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
625 exit( EXIT_FAILURE );
628 case 'L': /* print entries in LDIF format */
631 case 's': /* search scope */
632 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
633 scope = LDAP_SCOPE_BASE;
634 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
635 scope = LDAP_SCOPE_ONELEVEL;
636 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
637 || ( strcasecmp( optarg, "children" ) == 0 ))
639 scope = LDAP_SCOPE_SUBORDINATE;
640 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
641 scope = LDAP_SCOPE_SUBTREE;
643 fprintf( stderr, _("scope should be base, one, or sub\n") );
647 case 'S': /* sort attribute */
648 sortattr = strdup( optarg );
650 case 't': /* write attribute values to TMPDIR files */
653 case 'T': /* tmpdir */
654 if( tmpdir ) free( tmpdir );
655 tmpdir = strdup( optarg );
657 case 'u': /* include UFN */
660 case 'z': /* size limit */
661 if ( strcasecmp( optarg, "none" ) == 0 ) {
664 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
665 sizelimit = LDAP_MAXINT;
668 ival = strtol( optarg, &next, 10 );
669 if ( next == NULL || next[0] != '\0' ) {
671 _("Unable to parse size limit \"%s\"\n"), optarg );
672 exit( EXIT_FAILURE );
676 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
677 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
679 exit( EXIT_FAILURE );
690 private_conn_setup( LDAP *ld )
693 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
694 != LDAP_OPT_SUCCESS )
696 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
697 exit( EXIT_FAILURE );
700 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
701 != LDAP_OPT_SUCCESS )
704 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
705 exit( EXIT_FAILURE );
708 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
709 != LDAP_OPT_SUCCESS )
712 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
713 exit( EXIT_FAILURE );
718 main( int argc, char **argv )
720 char *filtpattern, **attrs = NULL, line[BUFSIZ];
722 int rc, rc1, i, first;
724 BerElement *seber = NULL, *vrber = NULL;
726 BerElement *syncber = NULL;
727 struct berval *syncbvalp = NULL;
730 tool_init( TOOL_SEARCH );
732 npagedresponses = npagedentries = npagedreferences =
733 npagedextended = npagedpartial = 0;
735 prog = lutil_progname( "ldapsearch", argc, argv );
737 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
738 (def_tmpdir = getenv("TMP")) == NULL &&
739 (def_tmpdir = getenv("TEMP")) == NULL )
741 def_tmpdir = LDAP_TMPDIR;
745 def_tmpdir = LDAP_TMPDIR;
747 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
749 if( def_urlpre == NULL ) {
754 sprintf( def_urlpre, "file:///%s/",
755 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
757 urlize( def_urlpre );
759 tool_args( argc, argv );
761 if (( argc - optind < 1 ) ||
762 ( *argv[optind] != '(' /*')'*/ &&
763 ( strchr( argv[optind], '=' ) == NULL ) ) )
765 filtpattern = "(objectclass=*)";
767 filtpattern = argv[optind++];
770 if ( argv[optind] != NULL ) {
771 attrs = &argv[optind];
774 if ( infile != NULL ) {
777 if ( infile[0] == '-' && infile[1] == '\0' ) {
779 } else if (( fp = fopen( infile, "r" )) == NULL ) {
784 for( i=0 ; filtpattern[i] ; i++ ) {
785 if( filtpattern[i] == '%' ) {
787 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
794 if( filtpattern[i+1] != 's' ) {
795 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
803 if ( tmpdir == NULL ) {
806 if ( urlpre == NULL )
810 if( urlpre == NULL ) {
811 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
813 if( urlpre == NULL ) {
818 sprintf( urlpre, "file:///%s/",
819 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
827 ld = tool_conn_setup( 0, &private_conn_setup );
829 if ( pw_file || want_bindpw ) {
831 rc = lutil_get_filed_password( pw_file, &passwd );
832 if( rc ) return EXIT_FAILURE;
834 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
835 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
842 save_nctrls = nctrls;
845 #ifdef LDAP_CONTROL_DONTUSECOPY
848 #ifdef LDAP_CONTROL_X_DEREF
856 || valuesReturnFilter )
859 #ifdef LDAP_CONTROL_DONTUSECOPY
865 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
866 c[i].ldctl_value.bv_val = NULL;
867 c[i].ldctl_value.bv_len = 0;
868 c[i].ldctl_iscritical = dontUseCopy == 2;
878 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
879 c[i].ldctl_value.bv_val = NULL;
880 c[i].ldctl_value.bv_len = 0;
881 c[i].ldctl_iscritical = domainScope > 1;
890 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
894 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
896 ber_free( seber, 1 );
897 fprintf( stderr, _("Subentries control encoding error!\n") );
901 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
905 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
906 c[i].ldctl_iscritical = subentries < 1;
915 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
919 if ( sync_cookie.bv_len == 0 ) {
920 err = ber_printf( syncber, "{e}", abs(ldapsync) );
922 err = ber_printf( syncber, "{eO}", abs(ldapsync),
927 ber_free( syncber, 1 );
928 fprintf( stderr, _("ldap sync control encoding error!\n") );
932 if ( ber_flatten( syncber, &syncbvalp ) == -1 ) {
936 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
937 c[i].ldctl_value = (*syncbvalp);
938 c[i].ldctl_iscritical = ldapsync < 0;
942 if ( valuesReturnFilter ) {
947 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
951 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
952 ber_free( vrber, 1 );
953 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
957 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
961 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
962 c[i].ldctl_iscritical = valuesReturnFilter > 1;
966 if ( pagedResults ) {
971 if ( ldap_create_page_control_value( ld,
972 pageSize, &pr_cookie, &c[i].ldctl_value ) )
977 if ( pr_cookie.bv_val != NULL ) {
978 ber_memfree( pr_cookie.bv_val );
979 pr_cookie.bv_val = NULL;
980 pr_cookie.bv_len = 0;
983 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
984 c[i].ldctl_iscritical = pagedResults > 1;
993 if ( ldap_create_sort_control_value( ld,
994 sss_keys, &c[i].ldctl_value ) )
999 c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
1000 c[i].ldctl_iscritical = sss > 1;
1004 #ifdef LDAP_CONTROL_X_DEREF
1006 if ( derefval.bv_val == NULL ) {
1009 assert( ds != NULL );
1011 if ( ldap_create_deref_control_value( ld, ds, &derefval ) != LDAP_SUCCESS ) {
1012 return EXIT_FAILURE;
1015 for ( i = 0; ds[ i ].derefAttr != NULL; i++ ) {
1016 ldap_memfree( ds[ i ].derefAttr );
1017 ldap_charray_free( ds[ i ].attributes );
1024 exit( EXIT_FAILURE );
1027 c[ i ].ldctl_iscritical = derefcrit > 1;
1028 c[ i ].ldctl_oid = LDAP_CONTROL_X_DEREF;
1029 c[ i ].ldctl_value = derefval;
1032 #endif /* LDAP_CONTROL_X_DEREF */
1035 tool_server_controls( ld, c, i );
1037 ber_free( seber, 1 );
1038 ber_free( vrber, 1 );
1040 /* step back to the original number of controls, so that
1041 * those set while parsing args are preserved */
1042 nctrls = save_nctrls;
1045 fprintf( stderr, _("filter%s: %s\nrequesting: "),
1046 infile != NULL ? _(" pattern") : "",
1049 if ( attrs == NULL ) {
1050 fprintf( stderr, _("All userApplication attributes") );
1052 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1053 fprintf( stderr, "%s ", attrs[ i ] );
1056 fprintf( stderr, "\n" );
1060 printf( _("# extended LDIF\n") );
1061 } else if ( ldif < 3 ) {
1062 printf( _("version: %d\n\n"), 1 );
1066 char *realbase = base;
1068 if ( realbase == NULL ) {
1069 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
1073 printf(_("# LDAPv%d\n"), protocol);
1074 printf(_("# base <%s>%s with scope %s\n"),
1075 realbase ? realbase : "",
1076 ( realbase == NULL || realbase != base ) ? " (default)" : "",
1077 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
1078 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
1079 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
1081 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
1083 printf(_("# requesting: "));
1085 if ( attrs == NULL ) {
1088 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1089 printf( "%s ", attrs[ i ] );
1093 if ( manageDSAit ) {
1094 printf(_("\n# with manageDSAit %scontrol"),
1095 manageDSAit > 1 ? _("critical ") : "" );
1098 printf(_("\n# with noop %scontrol"),
1099 noop > 1 ? _("critical ") : "" );
1102 printf(_("\n# with subentries %scontrol: %s"),
1103 subentries < 0 ? _("critical ") : "",
1104 abs(subentries) == 1 ? "false" : "true" );
1106 if ( valuesReturnFilter ) {
1107 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1108 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1110 if ( pagedResults ) {
1111 printf(_("\n# with pagedResults %scontrol: size=%d"),
1112 (pagedResults > 1) ? _("critical ") : "",
1116 printf(_("\n# with server side sorting %scontrol"),
1117 sss > 1 ? _("critical ") : "" );
1119 #ifdef LDAP_CONTROL_X_DEREF
1121 printf(_("\n# with dereference %scontrol"),
1122 sss > 1 ? _("critical ") : "" );
1126 printf( _("\n#\n\n") );
1128 if ( realbase && realbase != base ) {
1129 ldap_memfree( realbase );
1133 if ( infile == NULL ) {
1134 rc = dosearch( ld, base, scope, NULL, filtpattern,
1135 attrs, attrsonly, NULL, NULL, NULL, -1 );
1140 while ( fgets( line, sizeof( line ), fp ) != NULL ) {
1141 line[ strlen( line ) - 1 ] = '\0';
1147 rc1 = dosearch( ld, base, scope, filtpattern, line,
1148 attrs, attrsonly, NULL, NULL, NULL, -1 );
1156 if ( fp != stdin ) {
1161 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1163 int i, moreEntries, tmpSize;
1165 /* Loop to get the next pages when
1166 * enter is pressed on the terminal.
1168 if ( pagePrompt != 0 ) {
1169 if ( entriesLeft > 0 ) {
1170 printf( _("Estimate entries: %d\n"), entriesLeft );
1172 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1175 moreEntries = getchar();
1176 while ( moreEntries != EOF && moreEntries != '\n' ) {
1177 if ( i < (int)sizeof(buf) - 1 ) {
1178 buf[i] = moreEntries;
1181 moreEntries = getchar();
1185 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1186 int num = sscanf( buf, "%d", &tmpSize );
1189 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1190 return EXIT_FAILURE;
1193 pageSize = (ber_int_t)tmpSize;
1202 if ( base != NULL ) {
1203 ber_memfree( base );
1205 if ( control != NULL ) {
1206 ber_memfree( control );
1208 if ( sss_keys != NULL ) {
1209 ldap_free_sort_keylist( sss_keys );
1211 if ( derefval.bv_val != NULL ) {
1212 ldap_memfree( derefval.bv_val );
1216 for ( ; save_nctrls-- > 0; ) {
1217 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1227 static int dosearch(
1235 LDAPControl **sctrls,
1236 LDAPControl **cctrls,
1237 struct timeval *timeout,
1247 LDAPMessage *res, *msg;
1249 char *retoid = NULL;
1250 struct berval *retdata = NULL;
1251 int nresponses_psearch = -1;
1252 int cancel_msgid = -1;
1254 if( filtpatt != NULL ) {
1255 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1, outlen;
1256 filter = malloc( max_fsize );
1257 if( filter == NULL ) {
1259 return EXIT_FAILURE;
1262 outlen = snprintf( filter, max_fsize, filtpatt, value );
1263 if( outlen >= max_fsize ) {
1264 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1266 return EXIT_FAILURE;
1270 fprintf( stderr, _("filter: %s\n"), filter );
1274 printf( _("#\n# filter: %s\n#\n"), filter );
1282 if ( filtpatt != NULL ) {
1285 return LDAP_SUCCESS;
1288 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1289 sctrls, cctrls, timeout, sizelimit, &msgid );
1291 if ( filtpatt != NULL ) {
1295 if( rc != LDAP_SUCCESS ) {
1296 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1297 prog, ldap_err2string( rc ), rc );
1301 nresponses = nentries = nreferences = nextended = npartial = 0;
1305 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1306 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1309 rc = tool_check_abandon( ld, msgid );
1315 (void) ldap_sort_entries( ld, &res,
1316 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1319 for ( msg = ldap_first_message( ld, res );
1321 msg = ldap_next_message( ld, msg ) )
1323 if ( nresponses++ ) putchar('\n');
1324 if ( nresponses_psearch >= 0 )
1325 nresponses_psearch++;
1327 switch( ldap_msgtype( msg ) ) {
1328 case LDAP_RES_SEARCH_ENTRY:
1330 print_entry( ld, msg, attrsonly );
1333 case LDAP_RES_SEARCH_REFERENCE:
1335 print_reference( ld, msg );
1338 case LDAP_RES_EXTENDED:
1340 print_extended( ld, msg );
1342 if ( ldap_msgid( msg ) == 0 ) {
1343 /* unsolicited extended operation */
1347 if ( cancel_msgid != -1 &&
1348 cancel_msgid == ldap_msgid( msg ) ) {
1349 printf(_("Cancelled \n"));
1350 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1355 case LDAP_RES_SEARCH_RESULT:
1356 /* pagedResults stuff is dealt with
1357 * in tool_print_ctrls(), called by
1358 * print_results(). */
1359 rc = print_result( ld, msg, 1 );
1360 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1366 case LDAP_RES_INTERMEDIATE:
1368 ldap_parse_intermediate( ld, msg,
1369 &retoid, &retdata, NULL, 0 );
1371 nresponses_psearch = 0;
1373 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1374 printf(_("SyncInfo Received\n"));
1375 ldap_memfree( retoid );
1376 ber_bvfree( retdata );
1380 print_partial( ld, msg );
1381 ldap_memfree( retoid );
1382 ber_bvfree( retdata );
1386 if ( ldapsync && sync_slimit != -1 &&
1387 nresponses_psearch >= sync_slimit ) {
1388 BerElement *msgidber = NULL;
1389 struct berval *msgidvalp = NULL;
1390 msgidber = ber_alloc_t(LBER_USE_DER);
1391 ber_printf(msgidber, "{i}", msgid);
1392 ber_flatten(msgidber, &msgidvalp);
1393 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1394 msgidvalp, NULL, NULL, &cancel_msgid);
1395 nresponses_psearch = -1;
1399 ldap_msgfree( res );
1404 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1408 ldap_msgfree( res );
1410 if ( pagedResults ) {
1411 npagedresponses += nresponses;
1412 npagedentries += nentries;
1413 npagedextended += nextended;
1414 npagedpartial += npartial;
1415 npagedreferences += nreferences;
1416 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1417 printf( _("\n# numResponses: %d\n"), npagedresponses );
1418 if( npagedentries ) {
1419 printf( _("# numEntries: %d\n"), npagedentries );
1421 if( npagedextended ) {
1422 printf( _("# numExtended: %d\n"), npagedextended );
1424 if( npagedpartial ) {
1425 printf( _("# numPartial: %d\n"), npagedpartial );
1427 if( npagedreferences ) {
1428 printf( _("# numReferences: %d\n"), npagedreferences );
1431 } else if ( ldif < 2 ) {
1432 printf( _("\n# numResponses: %d\n"), nresponses );
1433 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1434 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1435 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1436 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1442 /* This is the proposed new way of doing things.
1443 * It is more efficient, but the API is non-standard.
1452 char tmpfname[ 256 ];
1455 BerElement *ber = NULL;
1456 struct berval bv, *bvals, **bvp = &bvals;
1457 LDAPControl **ctrls = NULL;
1460 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1463 ufn = ldap_dn2ufn( bv.bv_val );
1464 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1466 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1468 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1469 if( rc != LDAP_SUCCESS ) {
1470 fprintf(stderr, _("print_entry: %d\n"), rc );
1471 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1472 exit( EXIT_FAILURE );
1476 tool_print_ctrls( ld, ctrls );
1477 ldap_controls_free( ctrls );
1482 ufn = ldap_dn2ufn( bv.bv_val );
1484 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1487 if( ufn != NULL ) ldap_memfree( ufn );
1489 if ( attrsonly ) bvp = NULL;
1491 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1493 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1495 if (bv.bv_val == NULL) break;
1498 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1500 } else if ( bvals ) {
1501 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1502 if ( vals2tmp > 1 || ( vals2tmp &&
1503 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1506 /* write value to file */
1507 snprintf( tmpfname, sizeof tmpfname,
1508 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1509 tmpdir, bv.bv_val );
1512 tmpfd = mkstemp( tmpfname );
1519 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1524 if ( fwrite( bvals[ i ].bv_val,
1525 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1534 snprintf( url, sizeof url, "%s%s", urlpre,
1535 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1538 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1541 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1542 bvals[ i ].bv_val, bvals[ i ].bv_len );
1545 ber_memfree( bvals );
1554 static void print_reference(
1556 LDAPMessage *reference )
1560 LDAPControl **ctrls;
1563 printf(_("# search reference\n"));
1566 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1568 if( rc != LDAP_SUCCESS ) {
1569 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1570 exit( EXIT_FAILURE );
1575 for( i=0; refs[i] != NULL; i++ ) {
1576 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1577 "ref", refs[i], strlen(refs[i]) );
1579 ber_memvfree( (void **) refs );
1583 tool_print_ctrls( ld, ctrls );
1584 ldap_controls_free( ctrls );
1588 static void print_extended(
1590 LDAPMessage *extended )
1593 char *retoid = NULL;
1594 struct berval *retdata = NULL;
1597 printf(_("# extended result response\n"));
1600 rc = ldap_parse_extended_result( ld, extended,
1601 &retoid, &retdata, 0 );
1603 if( rc != LDAP_SUCCESS ) {
1604 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1605 exit( EXIT_FAILURE );
1609 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1610 "extended", retoid, retoid ? strlen(retoid) : 0 );
1612 ber_memfree( retoid );
1616 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1617 "data", retdata->bv_val, retdata->bv_len );
1619 ber_bvfree( retdata );
1622 print_result( ld, extended, 0 );
1625 static void print_partial(
1627 LDAPMessage *partial )
1630 char *retoid = NULL;
1631 struct berval *retdata = NULL;
1632 LDAPControl **ctrls = NULL;
1635 printf(_("# extended partial response\n"));
1638 rc = ldap_parse_intermediate( ld, partial,
1639 &retoid, &retdata, &ctrls, 0 );
1641 if( rc != LDAP_SUCCESS ) {
1642 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1643 exit( EXIT_FAILURE );
1647 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1648 "partial", retoid, retoid ? strlen(retoid) : 0 );
1651 ber_memfree( retoid );
1655 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1656 "data", retdata->bv_val, retdata->bv_len );
1659 ber_bvfree( retdata );
1663 tool_print_ctrls( ld, ctrls );
1664 ldap_controls_free( ctrls );
1668 static int print_result(
1670 LDAPMessage *result, int search )
1674 char *matcheddn = NULL;
1677 LDAPControl **ctrls = NULL;
1681 printf(_("# search result\n"));
1684 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1688 rc = ldap_parse_result( ld, result,
1689 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1691 if( rc != LDAP_SUCCESS ) {
1692 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1693 exit( EXIT_FAILURE );
1698 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1700 } else if ( err != LDAP_SUCCESS ) {
1701 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1707 tool_write_ldif( LDIF_PUT_VALUE,
1708 "matchedDN", matcheddn, strlen(matcheddn) );
1710 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1714 ber_memfree( matcheddn );
1720 if ( err == LDAP_PARTIAL_RESULTS ) {
1723 for ( line = text; line != NULL; ) {
1724 char *next = strchr( line, '\n' );
1726 tool_write_ldif( LDIF_PUT_TEXT,
1728 next ? (size_t) (next - line) : strlen( line ));
1730 line = next ? next + 1 : NULL;
1734 tool_write_ldif( LDIF_PUT_TEXT, "text",
1735 text, strlen(text) );
1738 fprintf( stderr, _("Additional information: %s\n"), text );
1742 ber_memfree( text );
1747 for( i=0; refs[i] != NULL; i++ ) {
1749 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1751 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1755 ber_memvfree( (void **) refs );
1758 pr_morePagedResults = 0;
1761 tool_print_ctrls( ld, ctrls );
1762 ldap_controls_free( ctrls );