1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2009 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 if( 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 ) ) {
550 exit( EXIT_FAILURE );
554 c[ nctrls - 1 ].ldctl_oid = control;
557 if ( cvalue == NULL ) {
558 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
559 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
561 } else if ( cvalue[ 0 ] == ':' ) {
569 * to use ldif_parse_line2() */
571 ldif_parse_line2( &cvalue[ -2 ], &type,
576 c[ nctrls - 1 ].ldctl_value = value;
579 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
584 c[ nctrls - 1 ].ldctl_iscritical = crit;
587 fprintf( stderr, _("Invalid search extension name: %s\n"),
592 case 'F': /* uri prefix */
593 if( urlpre ) free( urlpre );
594 urlpre = strdup( optarg );
596 case 'l': /* time limit */
597 if ( strcasecmp( optarg, "none" ) == 0 ) {
600 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
601 timelimit = LDAP_MAXINT;
604 ival = strtol( optarg, &next, 10 );
605 if ( next == NULL || next[0] != '\0' ) {
607 _("Unable to parse time limit \"%s\"\n"), optarg );
608 exit( EXIT_FAILURE );
612 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
613 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
615 exit( EXIT_FAILURE );
618 case 'L': /* print entries in LDIF format */
621 case 's': /* search scope */
622 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
623 scope = LDAP_SCOPE_BASE;
624 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
625 scope = LDAP_SCOPE_ONELEVEL;
626 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
627 || ( strcasecmp( optarg, "children" ) == 0 ))
629 scope = LDAP_SCOPE_SUBORDINATE;
630 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
631 scope = LDAP_SCOPE_SUBTREE;
633 fprintf( stderr, _("scope should be base, one, or sub\n") );
637 case 'S': /* sort attribute */
638 sortattr = strdup( optarg );
640 case 't': /* write attribute values to TMPDIR files */
643 case 'T': /* tmpdir */
644 if( tmpdir ) free( tmpdir );
645 tmpdir = strdup( optarg );
647 case 'u': /* include UFN */
650 case 'z': /* size limit */
651 if ( strcasecmp( optarg, "none" ) == 0 ) {
654 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
655 sizelimit = LDAP_MAXINT;
658 ival = strtol( optarg, &next, 10 );
659 if ( next == NULL || next[0] != '\0' ) {
661 _("Unable to parse size limit \"%s\"\n"), optarg );
662 exit( EXIT_FAILURE );
666 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
667 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
669 exit( EXIT_FAILURE );
680 private_conn_setup( LDAP *ld )
683 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
684 != LDAP_OPT_SUCCESS )
686 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
687 exit( EXIT_FAILURE );
690 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
691 != LDAP_OPT_SUCCESS )
694 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
695 exit( EXIT_FAILURE );
698 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
699 != LDAP_OPT_SUCCESS )
702 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
703 exit( EXIT_FAILURE );
708 main( int argc, char **argv )
710 char *filtpattern, **attrs = NULL, line[BUFSIZ];
712 int rc, rc1, i, first;
714 BerElement *seber = NULL, *vrber = NULL;
716 BerElement *syncber = NULL;
717 struct berval *syncbvalp = NULL;
720 tool_init( TOOL_SEARCH );
722 npagedresponses = npagedentries = npagedreferences =
723 npagedextended = npagedpartial = 0;
725 prog = lutil_progname( "ldapsearch", argc, argv );
727 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
728 (def_tmpdir = getenv("TMP")) == NULL &&
729 (def_tmpdir = getenv("TEMP")) == NULL )
731 def_tmpdir = LDAP_TMPDIR;
735 def_tmpdir = LDAP_TMPDIR;
737 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
739 if( def_urlpre == NULL ) {
744 sprintf( def_urlpre, "file:///%s/",
745 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
747 urlize( def_urlpre );
749 tool_args( argc, argv );
751 if (( argc - optind < 1 ) ||
752 ( *argv[optind] != '(' /*')'*/ &&
753 ( strchr( argv[optind], '=' ) == NULL ) ) )
755 filtpattern = "(objectclass=*)";
757 filtpattern = argv[optind++];
760 if ( argv[optind] != NULL ) {
761 attrs = &argv[optind];
764 if ( infile != NULL ) {
767 if ( infile[0] == '-' && infile[1] == '\0' ) {
769 } else if (( fp = fopen( infile, "r" )) == NULL ) {
774 for( i=0 ; filtpattern[i] ; i++ ) {
775 if( filtpattern[i] == '%' ) {
777 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
784 if( filtpattern[i+1] != 's' ) {
785 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
793 if ( tmpdir == NULL ) {
796 if ( urlpre == NULL )
800 if( urlpre == NULL ) {
801 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
803 if( urlpre == NULL ) {
808 sprintf( urlpre, "file:///%s/",
809 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
817 ld = tool_conn_setup( 0, &private_conn_setup );
819 if ( pw_file || want_bindpw ) {
821 rc = lutil_get_filed_password( pw_file, &passwd );
822 if( rc ) return EXIT_FAILURE;
824 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
825 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
832 save_nctrls = nctrls;
835 #ifdef LDAP_CONTROL_DONTUSECOPY
838 #ifdef LDAP_CONTROL_X_DEREF
846 || valuesReturnFilter )
849 #ifdef LDAP_CONTROL_DONTUSECOPY
855 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
856 c[i].ldctl_value.bv_val = NULL;
857 c[i].ldctl_value.bv_len = 0;
858 c[i].ldctl_iscritical = dontUseCopy > 1;
868 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
869 c[i].ldctl_value.bv_val = NULL;
870 c[i].ldctl_value.bv_len = 0;
871 c[i].ldctl_iscritical = domainScope > 1;
880 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
884 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
886 ber_free( seber, 1 );
887 fprintf( stderr, _("Subentries control encoding error!\n") );
891 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
895 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
896 c[i].ldctl_iscritical = subentries < 1;
905 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
909 if ( sync_cookie.bv_len == 0 ) {
910 err = ber_printf( syncber, "{e}", abs(ldapsync) );
912 err = ber_printf( syncber, "{eO}", abs(ldapsync),
917 ber_free( syncber, 1 );
918 fprintf( stderr, _("ldap sync control encoding error!\n") );
922 if ( ber_flatten( syncber, &syncbvalp ) == -1 ) {
926 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
927 c[i].ldctl_value = (*syncbvalp);
928 c[i].ldctl_iscritical = ldapsync < 0;
932 if ( valuesReturnFilter ) {
937 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
941 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
942 ber_free( vrber, 1 );
943 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
947 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
951 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
952 c[i].ldctl_iscritical = valuesReturnFilter > 1;
956 if ( pagedResults ) {
961 if ( ldap_create_page_control_value( ld,
962 pageSize, &pr_cookie, &c[i].ldctl_value ) )
967 if ( pr_cookie.bv_val != NULL ) {
968 ber_memfree( pr_cookie.bv_val );
969 pr_cookie.bv_val = NULL;
970 pr_cookie.bv_len = 0;
973 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
974 c[i].ldctl_iscritical = pagedResults > 1;
983 if ( ldap_create_sort_control_value( ld,
984 sss_keys, &c[i].ldctl_value ) )
989 c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
990 c[i].ldctl_iscritical = sss > 1;
994 #ifdef LDAP_CONTROL_X_DEREF
996 if ( derefval.bv_val == NULL ) {
999 assert( ds != NULL );
1001 if ( ldap_create_deref_control_value( ld, ds, &derefval ) != LDAP_SUCCESS ) {
1002 return EXIT_FAILURE;
1005 for ( i = 0; ds[ i ].derefAttr != NULL; i++ ) {
1006 ldap_memfree( ds[ i ].derefAttr );
1007 ldap_charray_free( ds[ i ].attributes );
1014 exit( EXIT_FAILURE );
1017 c[ i ].ldctl_iscritical = derefcrit > 1;
1018 c[ i ].ldctl_oid = LDAP_CONTROL_X_DEREF;
1019 c[ i ].ldctl_value = derefval;
1022 #endif /* LDAP_CONTROL_X_DEREF */
1025 tool_server_controls( ld, c, i );
1027 ber_free( seber, 1 );
1028 ber_free( vrber, 1 );
1030 /* step back to the original number of controls, so that
1031 * those set while parsing args are preserved */
1032 nctrls = save_nctrls;
1035 fprintf( stderr, _("filter%s: %s\nrequesting: "),
1036 infile != NULL ? _(" pattern") : "",
1039 if ( attrs == NULL ) {
1040 fprintf( stderr, _("All userApplication attributes") );
1042 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1043 fprintf( stderr, "%s ", attrs[ i ] );
1046 fprintf( stderr, "\n" );
1050 printf( _("# extended LDIF\n") );
1051 } else if ( ldif < 3 ) {
1052 printf( _("version: %d\n\n"), 1 );
1056 char *realbase = base;
1058 if ( realbase == NULL ) {
1059 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
1063 printf(_("# LDAPv%d\n"), protocol);
1064 printf(_("# base <%s>%s with scope %s\n"),
1065 realbase ? realbase : "",
1066 ( realbase == NULL || realbase != base ) ? " (default)" : "",
1067 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
1068 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
1069 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
1071 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
1073 printf(_("# requesting: "));
1075 if ( attrs == NULL ) {
1078 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1079 printf( "%s ", attrs[ i ] );
1083 if ( manageDSAit ) {
1084 printf(_("\n# with manageDSAit %scontrol"),
1085 manageDSAit > 1 ? _("critical ") : "" );
1088 printf(_("\n# with noop %scontrol"),
1089 noop > 1 ? _("critical ") : "" );
1092 printf(_("\n# with subentries %scontrol: %s"),
1093 subentries < 0 ? _("critical ") : "",
1094 abs(subentries) == 1 ? "false" : "true" );
1096 if ( valuesReturnFilter ) {
1097 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1098 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1100 if ( pagedResults ) {
1101 printf(_("\n# with pagedResults %scontrol: size=%d"),
1102 (pagedResults > 1) ? _("critical ") : "",
1106 printf(_("\n# with server side sorting %scontrol"),
1107 sss > 1 ? _("critical ") : "" );
1109 #ifdef LDAP_CONTROL_X_DEREF
1111 printf(_("\n# with dereference %scontrol"),
1112 sss > 1 ? _("critical ") : "" );
1116 printf( _("\n#\n\n") );
1118 if ( realbase && realbase != base ) {
1119 ldap_memfree( realbase );
1123 if ( infile == NULL ) {
1124 rc = dosearch( ld, base, scope, NULL, filtpattern,
1125 attrs, attrsonly, NULL, NULL, NULL, -1 );
1130 while ( fgets( line, sizeof( line ), fp ) != NULL ) {
1131 line[ strlen( line ) - 1 ] = '\0';
1137 rc1 = dosearch( ld, base, scope, filtpattern, line,
1138 attrs, attrsonly, NULL, NULL, NULL, -1 );
1146 if ( fp != stdin ) {
1151 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1153 int i, moreEntries, tmpSize;
1155 /* Loop to get the next pages when
1156 * enter is pressed on the terminal.
1158 if ( pagePrompt != 0 ) {
1159 if ( entriesLeft > 0 ) {
1160 printf( _("Estimate entries: %d\n"), entriesLeft );
1162 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1165 moreEntries = getchar();
1166 while ( moreEntries != EOF && moreEntries != '\n' ) {
1167 if ( i < (int)sizeof(buf) - 1 ) {
1168 buf[i] = moreEntries;
1171 moreEntries = getchar();
1175 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1176 int num = sscanf( buf, "%d", &tmpSize );
1179 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1180 return EXIT_FAILURE;
1183 pageSize = (ber_int_t)tmpSize;
1192 if ( base != NULL ) {
1193 ber_memfree( base );
1195 if ( control != NULL ) {
1196 ber_memfree( control );
1198 if ( sss_keys != NULL ) {
1199 ldap_free_sort_keylist( sss_keys );
1201 if ( derefval.bv_val != NULL ) {
1202 ldap_memfree( derefval.bv_val );
1206 for ( ; save_nctrls-- > 0; ) {
1207 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1217 static int dosearch(
1225 LDAPControl **sctrls,
1226 LDAPControl **cctrls,
1227 struct timeval *timeout,
1237 LDAPMessage *res, *msg;
1239 char *retoid = NULL;
1240 struct berval *retdata = NULL;
1241 int nresponses_psearch = -1;
1242 int cancel_msgid = -1;
1244 if( filtpatt != NULL ) {
1245 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1, outlen;
1246 filter = malloc( max_fsize );
1247 if( filter == NULL ) {
1249 return EXIT_FAILURE;
1252 outlen = snprintf( filter, max_fsize, filtpatt, value );
1253 if( outlen >= max_fsize ) {
1254 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1256 return EXIT_FAILURE;
1260 fprintf( stderr, _("filter: %s\n"), filter );
1264 printf( _("#\n# filter: %s\n#\n"), filter );
1272 if ( filtpatt != NULL ) {
1275 return LDAP_SUCCESS;
1278 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1279 sctrls, cctrls, timeout, sizelimit, &msgid );
1281 if ( filtpatt != NULL ) {
1285 if( rc != LDAP_SUCCESS ) {
1286 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1287 prog, ldap_err2string( rc ), rc );
1291 nresponses = nentries = nreferences = nextended = npartial = 0;
1295 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1296 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1299 rc = tool_check_abandon( ld, msgid );
1305 (void) ldap_sort_entries( ld, &res,
1306 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1309 for ( msg = ldap_first_message( ld, res );
1311 msg = ldap_next_message( ld, msg ) )
1313 if ( nresponses++ ) putchar('\n');
1314 if ( nresponses_psearch >= 0 )
1315 nresponses_psearch++;
1317 switch( ldap_msgtype( msg ) ) {
1318 case LDAP_RES_SEARCH_ENTRY:
1320 print_entry( ld, msg, attrsonly );
1323 case LDAP_RES_SEARCH_REFERENCE:
1325 print_reference( ld, msg );
1328 case LDAP_RES_EXTENDED:
1330 print_extended( ld, msg );
1332 if ( ldap_msgid( msg ) == 0 ) {
1333 /* unsolicited extended operation */
1337 if ( cancel_msgid != -1 &&
1338 cancel_msgid == ldap_msgid( msg ) ) {
1339 printf(_("Cancelled \n"));
1340 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1345 case LDAP_RES_SEARCH_RESULT:
1346 /* pagedResults stuff is dealt with
1347 * in tool_print_ctrls(), called by
1348 * print_results(). */
1349 rc = print_result( ld, msg, 1 );
1350 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1356 case LDAP_RES_INTERMEDIATE:
1358 ldap_parse_intermediate( ld, msg,
1359 &retoid, &retdata, NULL, 0 );
1361 nresponses_psearch = 0;
1363 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1364 printf(_("SyncInfo Received\n"));
1365 ldap_memfree( retoid );
1366 ber_bvfree( retdata );
1370 print_partial( ld, msg );
1371 ldap_memfree( retoid );
1372 ber_bvfree( retdata );
1376 if ( ldapsync && sync_slimit != -1 &&
1377 nresponses_psearch >= sync_slimit ) {
1378 BerElement *msgidber = NULL;
1379 struct berval *msgidvalp = NULL;
1380 msgidber = ber_alloc_t(LBER_USE_DER);
1381 ber_printf(msgidber, "{i}", msgid);
1382 ber_flatten(msgidber, &msgidvalp);
1383 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1384 msgidvalp, NULL, NULL, &cancel_msgid);
1385 nresponses_psearch = -1;
1389 ldap_msgfree( res );
1394 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1398 ldap_msgfree( res );
1400 if ( pagedResults ) {
1401 npagedresponses += nresponses;
1402 npagedentries += nentries;
1403 npagedextended += nextended;
1404 npagedpartial += npartial;
1405 npagedreferences += nreferences;
1406 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1407 printf( _("\n# numResponses: %d\n"), npagedresponses );
1408 if( npagedentries ) {
1409 printf( _("# numEntries: %d\n"), npagedentries );
1411 if( npagedextended ) {
1412 printf( _("# numExtended: %d\n"), npagedextended );
1414 if( npagedpartial ) {
1415 printf( _("# numPartial: %d\n"), npagedpartial );
1417 if( npagedreferences ) {
1418 printf( _("# numReferences: %d\n"), npagedreferences );
1421 } else if ( ldif < 2 ) {
1422 printf( _("\n# numResponses: %d\n"), nresponses );
1423 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1424 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1425 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1426 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1432 /* This is the proposed new way of doing things.
1433 * It is more efficient, but the API is non-standard.
1442 char tmpfname[ 256 ];
1445 BerElement *ber = NULL;
1446 struct berval bv, *bvals, **bvp = &bvals;
1447 LDAPControl **ctrls = NULL;
1450 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1453 ufn = ldap_dn2ufn( bv.bv_val );
1454 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1456 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1458 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1459 if( rc != LDAP_SUCCESS ) {
1460 fprintf(stderr, _("print_entry: %d\n"), rc );
1461 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1462 exit( EXIT_FAILURE );
1466 tool_print_ctrls( ld, ctrls );
1467 ldap_controls_free( ctrls );
1472 ufn = ldap_dn2ufn( bv.bv_val );
1474 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1477 if( ufn != NULL ) ldap_memfree( ufn );
1479 if ( attrsonly ) bvp = NULL;
1481 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1483 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1485 if (bv.bv_val == NULL) break;
1488 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1490 } else if ( bvals ) {
1491 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1492 if ( vals2tmp > 1 || ( vals2tmp &&
1493 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1496 /* write value to file */
1497 snprintf( tmpfname, sizeof tmpfname,
1498 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1499 tmpdir, bv.bv_val );
1502 tmpfd = mkstemp( tmpfname );
1509 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1514 if ( fwrite( bvals[ i ].bv_val,
1515 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1524 snprintf( url, sizeof url, "%s%s", urlpre,
1525 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1528 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1531 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1532 bvals[ i ].bv_val, bvals[ i ].bv_len );
1535 ber_memfree( bvals );
1544 static void print_reference(
1546 LDAPMessage *reference )
1550 LDAPControl **ctrls;
1553 printf(_("# search reference\n"));
1556 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1558 if( rc != LDAP_SUCCESS ) {
1559 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1560 exit( EXIT_FAILURE );
1565 for( i=0; refs[i] != NULL; i++ ) {
1566 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1567 "ref", refs[i], strlen(refs[i]) );
1569 ber_memvfree( (void **) refs );
1573 tool_print_ctrls( ld, ctrls );
1574 ldap_controls_free( ctrls );
1578 static void print_extended(
1580 LDAPMessage *extended )
1583 char *retoid = NULL;
1584 struct berval *retdata = NULL;
1587 printf(_("# extended result response\n"));
1590 rc = ldap_parse_extended_result( ld, extended,
1591 &retoid, &retdata, 0 );
1593 if( rc != LDAP_SUCCESS ) {
1594 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1595 exit( EXIT_FAILURE );
1599 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1600 "extended", retoid, retoid ? strlen(retoid) : 0 );
1602 ber_memfree( retoid );
1606 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1607 "data", retdata->bv_val, retdata->bv_len );
1609 ber_bvfree( retdata );
1612 print_result( ld, extended, 0 );
1615 static void print_partial(
1617 LDAPMessage *partial )
1620 char *retoid = NULL;
1621 struct berval *retdata = NULL;
1622 LDAPControl **ctrls = NULL;
1625 printf(_("# extended partial response\n"));
1628 rc = ldap_parse_intermediate( ld, partial,
1629 &retoid, &retdata, &ctrls, 0 );
1631 if( rc != LDAP_SUCCESS ) {
1632 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1633 exit( EXIT_FAILURE );
1637 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1638 "partial", retoid, retoid ? strlen(retoid) : 0 );
1641 ber_memfree( retoid );
1645 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1646 "data", retdata->bv_val, retdata->bv_len );
1649 ber_bvfree( retdata );
1653 tool_print_ctrls( ld, ctrls );
1654 ldap_controls_free( ctrls );
1658 static int print_result(
1660 LDAPMessage *result, int search )
1664 char *matcheddn = NULL;
1667 LDAPControl **ctrls = NULL;
1671 printf(_("# search result\n"));
1674 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1678 rc = ldap_parse_result( ld, result,
1679 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1681 if( rc != LDAP_SUCCESS ) {
1682 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1683 exit( EXIT_FAILURE );
1688 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1690 } else if ( err != LDAP_SUCCESS ) {
1691 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1697 tool_write_ldif( LDIF_PUT_VALUE,
1698 "matchedDN", matcheddn, strlen(matcheddn) );
1700 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1704 ber_memfree( matcheddn );
1710 if ( err == LDAP_PARTIAL_RESULTS ) {
1713 for ( line = text; line != NULL; ) {
1714 char *next = strchr( line, '\n' );
1716 tool_write_ldif( LDIF_PUT_TEXT,
1718 next ? (size_t) (next - line) : strlen( line ));
1720 line = next ? next + 1 : NULL;
1724 tool_write_ldif( LDIF_PUT_TEXT, "text",
1725 text, strlen(text) );
1728 fprintf( stderr, _("Additional information: %s\n"), text );
1732 ber_memfree( text );
1737 for( i=0; refs[i] != NULL; i++ ) {
1739 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1741 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1745 ber_memvfree( (void **) refs );
1748 pr_morePagedResults = 0;
1751 tool_print_ctrls( ld, ctrls );
1752 ldap_controls_free( ctrls );