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 for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ )
517 ds = ldap_memcalloc( ispecs + 1, sizeof( LDAPDerefSpec ) );
522 for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ ) {
525 ptr = strchr( specs[ ispecs ], ':' );
530 ds[ ispecs ].derefAttr = specs[ ispecs ];
532 ds[ ispecs ].attributes = ldap_str2charray( ptr, "," );
535 derefcrit = 1 + crit;
537 ldap_memfree( specs );
538 #endif /* LDAP_CONTROL_X_DEREF */
540 } else if ( tool_is_oid( control ) ) {
543 for ( i = 0; c[ i ].ldctl_oid != NULL; i++ ) {
544 if ( strcmp( control, c[ i ].ldctl_oid ) == 0 ) {
545 fprintf( stderr, "%s control previously specified\n", control );
546 exit( EXIT_FAILURE );
552 exit( EXIT_FAILURE );
556 c[ nctrls - 1 ].ldctl_oid = control;
559 if ( cvalue == NULL ) {
560 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
561 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
563 } else if ( cvalue[ 0 ] == ':' ) {
571 * to use ldif_parse_line2() */
573 ldif_parse_line2( &cvalue[ -2 ], &type,
578 c[ nctrls - 1 ].ldctl_value = value;
581 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
586 c[ nctrls - 1 ].ldctl_iscritical = crit;
589 fprintf( stderr, _("Invalid search extension name: %s\n"),
594 case 'F': /* uri prefix */
595 if( urlpre ) free( urlpre );
596 urlpre = strdup( optarg );
598 case 'l': /* time limit */
599 if ( strcasecmp( optarg, "none" ) == 0 ) {
602 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
603 timelimit = LDAP_MAXINT;
606 ival = strtol( optarg, &next, 10 );
607 if ( next == NULL || next[0] != '\0' ) {
609 _("Unable to parse time limit \"%s\"\n"), optarg );
610 exit( EXIT_FAILURE );
614 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
615 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
617 exit( EXIT_FAILURE );
620 case 'L': /* print entries in LDIF format */
623 case 's': /* search scope */
624 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
625 scope = LDAP_SCOPE_BASE;
626 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
627 scope = LDAP_SCOPE_ONELEVEL;
628 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
629 || ( strcasecmp( optarg, "children" ) == 0 ))
631 scope = LDAP_SCOPE_SUBORDINATE;
632 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
633 scope = LDAP_SCOPE_SUBTREE;
635 fprintf( stderr, _("scope should be base, one, or sub\n") );
639 case 'S': /* sort attribute */
640 sortattr = strdup( optarg );
642 case 't': /* write attribute values to TMPDIR files */
645 case 'T': /* tmpdir */
646 if( tmpdir ) free( tmpdir );
647 tmpdir = strdup( optarg );
649 case 'u': /* include UFN */
652 case 'z': /* size limit */
653 if ( strcasecmp( optarg, "none" ) == 0 ) {
656 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
657 sizelimit = LDAP_MAXINT;
660 ival = strtol( optarg, &next, 10 );
661 if ( next == NULL || next[0] != '\0' ) {
663 _("Unable to parse size limit \"%s\"\n"), optarg );
664 exit( EXIT_FAILURE );
668 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
669 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
671 exit( EXIT_FAILURE );
682 private_conn_setup( LDAP *ld )
685 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
686 != LDAP_OPT_SUCCESS )
688 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
689 exit( EXIT_FAILURE );
692 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
693 != LDAP_OPT_SUCCESS )
696 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
697 exit( EXIT_FAILURE );
700 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
701 != LDAP_OPT_SUCCESS )
704 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
705 exit( EXIT_FAILURE );
710 main( int argc, char **argv )
712 char *filtpattern, **attrs = NULL, line[BUFSIZ];
714 int rc, rc1, i, first;
716 BerElement *seber = NULL, *vrber = NULL;
718 BerElement *syncber = NULL;
719 struct berval *syncbvalp = NULL;
722 tool_init( TOOL_SEARCH );
724 npagedresponses = npagedentries = npagedreferences =
725 npagedextended = npagedpartial = 0;
727 prog = lutil_progname( "ldapsearch", argc, argv );
729 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
730 (def_tmpdir = getenv("TMP")) == NULL &&
731 (def_tmpdir = getenv("TEMP")) == NULL )
733 def_tmpdir = LDAP_TMPDIR;
737 def_tmpdir = LDAP_TMPDIR;
739 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
741 if( def_urlpre == NULL ) {
746 sprintf( def_urlpre, "file:///%s/",
747 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
749 urlize( def_urlpre );
751 tool_args( argc, argv );
753 if (( argc - optind < 1 ) ||
754 ( *argv[optind] != '(' /*')'*/ &&
755 ( strchr( argv[optind], '=' ) == NULL ) ) )
757 filtpattern = "(objectclass=*)";
759 filtpattern = argv[optind++];
762 if ( argv[optind] != NULL ) {
763 attrs = &argv[optind];
766 if ( infile != NULL ) {
769 if ( infile[0] == '-' && infile[1] == '\0' ) {
771 } else if (( fp = fopen( infile, "r" )) == NULL ) {
776 for( i=0 ; filtpattern[i] ; i++ ) {
777 if( filtpattern[i] == '%' ) {
779 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
786 if( filtpattern[i+1] != 's' ) {
787 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
795 if ( tmpdir == NULL ) {
798 if ( urlpre == NULL )
802 if( urlpre == NULL ) {
803 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
805 if( urlpre == NULL ) {
810 sprintf( urlpre, "file:///%s/",
811 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
819 ld = tool_conn_setup( 0, &private_conn_setup );
821 if ( pw_file || want_bindpw ) {
823 rc = lutil_get_filed_password( pw_file, &passwd );
824 if( rc ) return EXIT_FAILURE;
826 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
827 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
834 save_nctrls = nctrls;
837 #ifdef LDAP_CONTROL_DONTUSECOPY
840 #ifdef LDAP_CONTROL_X_DEREF
848 || valuesReturnFilter )
851 #ifdef LDAP_CONTROL_DONTUSECOPY
857 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
858 c[i].ldctl_value.bv_val = NULL;
859 c[i].ldctl_value.bv_len = 0;
860 c[i].ldctl_iscritical = dontUseCopy == 2;
870 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
871 c[i].ldctl_value.bv_val = NULL;
872 c[i].ldctl_value.bv_len = 0;
873 c[i].ldctl_iscritical = domainScope > 1;
882 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
886 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
888 ber_free( seber, 1 );
889 fprintf( stderr, _("Subentries control encoding error!\n") );
893 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
897 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
898 c[i].ldctl_iscritical = subentries < 1;
907 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
911 if ( sync_cookie.bv_len == 0 ) {
912 err = ber_printf( syncber, "{e}", abs(ldapsync) );
914 err = ber_printf( syncber, "{eO}", abs(ldapsync),
919 ber_free( syncber, 1 );
920 fprintf( stderr, _("ldap sync control encoding error!\n") );
924 if ( ber_flatten( syncber, &syncbvalp ) == -1 ) {
928 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
929 c[i].ldctl_value = (*syncbvalp);
930 c[i].ldctl_iscritical = ldapsync < 0;
934 if ( valuesReturnFilter ) {
939 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
943 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
944 ber_free( vrber, 1 );
945 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
949 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
953 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
954 c[i].ldctl_iscritical = valuesReturnFilter > 1;
958 if ( pagedResults ) {
963 if ( ldap_create_page_control_value( ld,
964 pageSize, &pr_cookie, &c[i].ldctl_value ) )
969 if ( pr_cookie.bv_val != NULL ) {
970 ber_memfree( pr_cookie.bv_val );
971 pr_cookie.bv_val = NULL;
972 pr_cookie.bv_len = 0;
975 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
976 c[i].ldctl_iscritical = pagedResults > 1;
985 if ( ldap_create_sort_control_value( ld,
986 sss_keys, &c[i].ldctl_value ) )
991 c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
992 c[i].ldctl_iscritical = sss > 1;
996 #ifdef LDAP_CONTROL_X_DEREF
998 if ( derefval.bv_val == NULL ) {
1000 if ( ldap_create_deref_control_value( ld, ds, &derefval ) != LDAP_SUCCESS ) {
1001 return EXIT_FAILURE;
1004 for ( i = 0; ds[ i ].derefAttr != NULL; i++ ) {
1005 ldap_memfree( ds[ i ].derefAttr );
1006 ldap_charray_free( ds[ i ].attributes );
1012 exit( EXIT_FAILURE );
1015 c[ i ].ldctl_iscritical = derefcrit > 1;
1016 c[ i ].ldctl_oid = LDAP_CONTROL_X_DEREF;
1017 c[ i ].ldctl_value = derefval;
1020 #endif /* LDAP_CONTROL_X_DEREF */
1023 tool_server_controls( ld, c, i );
1025 ber_free( seber, 1 );
1026 ber_free( vrber, 1 );
1028 /* step back to the original number of controls, so that
1029 * those set while parsing args are preserved */
1030 nctrls = save_nctrls;
1033 fprintf( stderr, _("filter%s: %s\nrequesting: "),
1034 infile != NULL ? _(" pattern") : "",
1037 if ( attrs == NULL ) {
1038 fprintf( stderr, _("All userApplication attributes") );
1040 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1041 fprintf( stderr, "%s ", attrs[ i ] );
1044 fprintf( stderr, "\n" );
1048 printf( _("# extended LDIF\n") );
1049 } else if ( ldif < 3 ) {
1050 printf( _("version: %d\n\n"), 1 );
1054 char *realbase = base;
1056 if ( realbase == NULL ) {
1057 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
1061 printf(_("# LDAPv%d\n"), protocol);
1062 printf(_("# base <%s>%s with scope %s\n"),
1063 realbase ? realbase : "",
1064 ( realbase == NULL || realbase != base ) ? " (default)" : "",
1065 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
1066 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
1067 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
1069 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
1071 printf(_("# requesting: "));
1073 if ( attrs == NULL ) {
1076 for ( i = 0; attrs[ i ] != NULL; ++i ) {
1077 printf( "%s ", attrs[ i ] );
1081 if ( manageDSAit ) {
1082 printf(_("\n# with manageDSAit %scontrol"),
1083 manageDSAit > 1 ? _("critical ") : "" );
1086 printf(_("\n# with noop %scontrol"),
1087 noop > 1 ? _("critical ") : "" );
1090 printf(_("\n# with subentries %scontrol: %s"),
1091 subentries < 0 ? _("critical ") : "",
1092 abs(subentries) == 1 ? "false" : "true" );
1094 if ( valuesReturnFilter ) {
1095 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1096 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1098 if ( pagedResults ) {
1099 printf(_("\n# with pagedResults %scontrol: size=%d"),
1100 (pagedResults > 1) ? _("critical ") : "",
1104 printf(_("\n# with server side sorting %scontrol"),
1105 sss > 1 ? _("critical ") : "" );
1107 #ifdef LDAP_CONTROL_X_DEREF
1109 printf(_("\n# with dereference %scontrol"),
1110 sss > 1 ? _("critical ") : "" );
1114 printf( _("\n#\n\n") );
1116 if ( realbase && realbase != base ) {
1117 ldap_memfree( realbase );
1121 if ( infile == NULL ) {
1122 rc = dosearch( ld, base, scope, NULL, filtpattern,
1123 attrs, attrsonly, NULL, NULL, NULL, -1 );
1128 while ( fgets( line, sizeof( line ), fp ) != NULL ) {
1129 line[ strlen( line ) - 1 ] = '\0';
1135 rc1 = dosearch( ld, base, scope, filtpattern, line,
1136 attrs, attrsonly, NULL, NULL, NULL, -1 );
1144 if ( fp != stdin ) {
1149 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1151 int i, moreEntries, tmpSize;
1153 /* Loop to get the next pages when
1154 * enter is pressed on the terminal.
1156 if ( pagePrompt != 0 ) {
1157 if ( entriesLeft > 0 ) {
1158 printf( _("Estimate entries: %d\n"), entriesLeft );
1160 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1163 moreEntries = getchar();
1164 while ( moreEntries != EOF && moreEntries != '\n' ) {
1165 if ( i < (int)sizeof(buf) - 1 ) {
1166 buf[i] = moreEntries;
1169 moreEntries = getchar();
1173 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1174 int num = sscanf( buf, "%d", &tmpSize );
1177 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1178 return EXIT_FAILURE;
1181 pageSize = (ber_int_t)tmpSize;
1190 if ( base != NULL ) {
1191 ber_memfree( base );
1193 if ( control != NULL ) {
1194 ber_memfree( control );
1196 if ( sss_keys != NULL ) {
1197 ldap_free_sort_keylist( sss_keys );
1201 for ( ; save_nctrls-- > 0; ) {
1202 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1212 static int dosearch(
1220 LDAPControl **sctrls,
1221 LDAPControl **cctrls,
1222 struct timeval *timeout,
1232 LDAPMessage *res, *msg;
1234 char *retoid = NULL;
1235 struct berval *retdata = NULL;
1236 int nresponses_psearch = -1;
1237 int cancel_msgid = -1;
1239 if( filtpatt != NULL ) {
1240 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1, outlen;
1241 filter = malloc( max_fsize );
1242 if( filter == NULL ) {
1244 return EXIT_FAILURE;
1247 outlen = snprintf( filter, max_fsize, filtpatt, value );
1248 if( outlen >= max_fsize ) {
1249 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1251 return EXIT_FAILURE;
1255 fprintf( stderr, _("filter: %s\n"), filter );
1259 printf( _("#\n# filter: %s\n#\n"), filter );
1267 if ( filtpatt != NULL ) {
1270 return LDAP_SUCCESS;
1273 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1274 sctrls, cctrls, timeout, sizelimit, &msgid );
1276 if ( filtpatt != NULL ) {
1280 if( rc != LDAP_SUCCESS ) {
1281 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1282 prog, ldap_err2string( rc ), rc );
1286 nresponses = nentries = nreferences = nextended = npartial = 0;
1290 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1291 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1294 rc = tool_check_abandon( ld, msgid );
1300 (void) ldap_sort_entries( ld, &res,
1301 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1304 for ( msg = ldap_first_message( ld, res );
1306 msg = ldap_next_message( ld, msg ) )
1308 if ( nresponses++ ) putchar('\n');
1309 if ( nresponses_psearch >= 0 )
1310 nresponses_psearch++;
1312 switch( ldap_msgtype( msg ) ) {
1313 case LDAP_RES_SEARCH_ENTRY:
1315 print_entry( ld, msg, attrsonly );
1318 case LDAP_RES_SEARCH_REFERENCE:
1320 print_reference( ld, msg );
1323 case LDAP_RES_EXTENDED:
1325 print_extended( ld, msg );
1327 if ( ldap_msgid( msg ) == 0 ) {
1328 /* unsolicited extended operation */
1332 if ( cancel_msgid != -1 &&
1333 cancel_msgid == ldap_msgid( msg ) ) {
1334 printf(_("Cancelled \n"));
1335 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1340 case LDAP_RES_SEARCH_RESULT:
1341 /* pagedResults stuff is dealt with
1342 * in tool_print_ctrls(), called by
1343 * print_results(). */
1344 rc = print_result( ld, msg, 1 );
1345 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1351 case LDAP_RES_INTERMEDIATE:
1353 ldap_parse_intermediate( ld, msg,
1354 &retoid, &retdata, NULL, 0 );
1356 nresponses_psearch = 0;
1358 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1359 printf(_("SyncInfo Received\n"));
1360 ldap_memfree( retoid );
1361 ber_bvfree( retdata );
1365 print_partial( ld, msg );
1366 ldap_memfree( retoid );
1367 ber_bvfree( retdata );
1371 if ( ldapsync && sync_slimit != -1 &&
1372 nresponses_psearch >= sync_slimit ) {
1373 BerElement *msgidber = NULL;
1374 struct berval *msgidvalp = NULL;
1375 msgidber = ber_alloc_t(LBER_USE_DER);
1376 ber_printf(msgidber, "{i}", msgid);
1377 ber_flatten(msgidber, &msgidvalp);
1378 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1379 msgidvalp, NULL, NULL, &cancel_msgid);
1380 nresponses_psearch = -1;
1384 ldap_msgfree( res );
1389 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1393 ldap_msgfree( res );
1395 if ( pagedResults ) {
1396 npagedresponses += nresponses;
1397 npagedentries += nentries;
1398 npagedextended += nextended;
1399 npagedpartial += npartial;
1400 npagedreferences += nreferences;
1401 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1402 printf( _("\n# numResponses: %d\n"), npagedresponses );
1403 if( npagedentries ) {
1404 printf( _("# numEntries: %d\n"), npagedentries );
1406 if( npagedextended ) {
1407 printf( _("# numExtended: %d\n"), npagedextended );
1409 if( npagedpartial ) {
1410 printf( _("# numPartial: %d\n"), npagedpartial );
1412 if( npagedreferences ) {
1413 printf( _("# numReferences: %d\n"), npagedreferences );
1416 } else if ( ldif < 2 ) {
1417 printf( _("\n# numResponses: %d\n"), nresponses );
1418 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1419 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1420 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1421 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1427 /* This is the proposed new way of doing things.
1428 * It is more efficient, but the API is non-standard.
1437 char tmpfname[ 256 ];
1440 BerElement *ber = NULL;
1441 struct berval bv, *bvals, **bvp = &bvals;
1442 LDAPControl **ctrls = NULL;
1445 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1448 ufn = ldap_dn2ufn( bv.bv_val );
1449 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1451 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1453 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1454 if( rc != LDAP_SUCCESS ) {
1455 fprintf(stderr, _("print_entry: %d\n"), rc );
1456 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1457 exit( EXIT_FAILURE );
1461 tool_print_ctrls( ld, ctrls );
1462 ldap_controls_free( ctrls );
1467 ufn = ldap_dn2ufn( bv.bv_val );
1469 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1472 if( ufn != NULL ) ldap_memfree( ufn );
1474 if ( attrsonly ) bvp = NULL;
1476 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1478 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1480 if (bv.bv_val == NULL) break;
1483 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1485 } else if ( bvals ) {
1486 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1487 if ( vals2tmp > 1 || ( vals2tmp &&
1488 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1491 /* write value to file */
1492 snprintf( tmpfname, sizeof tmpfname,
1493 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1494 tmpdir, bv.bv_val );
1497 tmpfd = mkstemp( tmpfname );
1504 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1509 if ( fwrite( bvals[ i ].bv_val,
1510 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1519 snprintf( url, sizeof url, "%s%s", urlpre,
1520 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1523 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1526 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1527 bvals[ i ].bv_val, bvals[ i ].bv_len );
1530 ber_memfree( bvals );
1539 static void print_reference(
1541 LDAPMessage *reference )
1545 LDAPControl **ctrls;
1548 printf(_("# search reference\n"));
1551 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1553 if( rc != LDAP_SUCCESS ) {
1554 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1555 exit( EXIT_FAILURE );
1560 for( i=0; refs[i] != NULL; i++ ) {
1561 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1562 "ref", refs[i], strlen(refs[i]) );
1564 ber_memvfree( (void **) refs );
1568 tool_print_ctrls( ld, ctrls );
1569 ldap_controls_free( ctrls );
1573 static void print_extended(
1575 LDAPMessage *extended )
1578 char *retoid = NULL;
1579 struct berval *retdata = NULL;
1582 printf(_("# extended result response\n"));
1585 rc = ldap_parse_extended_result( ld, extended,
1586 &retoid, &retdata, 0 );
1588 if( rc != LDAP_SUCCESS ) {
1589 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1590 exit( EXIT_FAILURE );
1594 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1595 "extended", retoid, retoid ? strlen(retoid) : 0 );
1597 ber_memfree( retoid );
1601 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1602 "data", retdata->bv_val, retdata->bv_len );
1604 ber_bvfree( retdata );
1607 print_result( ld, extended, 0 );
1610 static void print_partial(
1612 LDAPMessage *partial )
1615 char *retoid = NULL;
1616 struct berval *retdata = NULL;
1617 LDAPControl **ctrls = NULL;
1620 printf(_("# extended partial response\n"));
1623 rc = ldap_parse_intermediate( ld, partial,
1624 &retoid, &retdata, &ctrls, 0 );
1626 if( rc != LDAP_SUCCESS ) {
1627 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1628 exit( EXIT_FAILURE );
1632 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1633 "partial", retoid, retoid ? strlen(retoid) : 0 );
1636 ber_memfree( retoid );
1640 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1641 "data", retdata->bv_val, retdata->bv_len );
1644 ber_bvfree( retdata );
1648 tool_print_ctrls( ld, ctrls );
1649 ldap_controls_free( ctrls );
1653 static int print_result(
1655 LDAPMessage *result, int search )
1659 char *matcheddn = NULL;
1662 LDAPControl **ctrls = NULL;
1666 printf(_("# search result\n"));
1669 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1673 rc = ldap_parse_result( ld, result,
1674 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1676 if( rc != LDAP_SUCCESS ) {
1677 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1678 exit( EXIT_FAILURE );
1683 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1685 } else if ( err != LDAP_SUCCESS ) {
1686 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1692 tool_write_ldif( LDIF_PUT_VALUE,
1693 "matchedDN", matcheddn, strlen(matcheddn) );
1695 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1699 ber_memfree( matcheddn );
1705 if ( err == LDAP_PARTIAL_RESULTS ) {
1708 for ( line = text; line != NULL; ) {
1709 char *next = strchr( line, '\n' );
1711 tool_write_ldif( LDIF_PUT_TEXT,
1713 next ? (size_t) (next - line) : strlen( line ));
1715 line = next ? next + 1 : NULL;
1719 tool_write_ldif( LDIF_PUT_TEXT, "text",
1720 text, strlen(text) );
1723 fprintf( stderr, _("Additional information: %s\n"), text );
1727 ber_memfree( text );
1732 for( i=0; refs[i] != NULL; i++ ) {
1734 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1736 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1740 ber_memvfree( (void **) refs );
1743 pr_morePagedResults = 0;
1746 tool_print_ctrls( ld, ctrls );
1747 ldap_controls_free( ctrls );