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> (matched values filter)\n"));
130 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
131 fprintf( stderr, _(" [!]sss=[-]<attr[:OID]>[/[-]<attr[:OID]>...] (server side sorting)\n"));
132 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
133 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
134 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
135 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
136 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
137 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
138 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
139 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
140 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
141 fprintf( stderr, _(" and version\n"));
142 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
143 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
144 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
145 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
146 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
147 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
148 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
150 exit( EXIT_FAILURE );
153 static void print_entry LDAP_P((
158 static void print_reference(
160 LDAPMessage *reference );
162 static void print_extended(
164 LDAPMessage *extended );
166 static void print_partial(
168 LDAPMessage *partial );
170 static int print_result(
175 static int dosearch LDAP_P((
183 LDAPControl **sctrls,
184 LDAPControl **cctrls,
185 struct timeval *timeout,
188 static char *tmpdir = NULL;
189 static char *urlpre = NULL;
190 static char *base = NULL;
191 static char *sortattr = NULL;
192 static int includeufn, vals2tmp = 0;
194 static int subentries = 0, valuesReturnFilter = 0;
195 static char *vrFilter = NULL;
197 #ifdef LDAP_CONTROL_DONTUSECOPY
198 static int dontUseCopy = 0;
201 static int domainScope = 0;
204 static LDAPSortKey **sss_keys = NULL;
206 static int ldapsync = 0;
207 static struct berval sync_cookie = { 0, NULL };
208 static int sync_slimit = -1;
210 /* cookie and morePagedResults moved to common.c */
211 static int pagedResults = 0;
212 static int pagePrompt = 1;
213 static ber_int_t pageSize = 0;
214 static ber_int_t entriesLeft = 0;
215 static int npagedresponses;
216 static int npagedentries;
217 static int npagedreferences;
218 static int npagedextended;
219 static int npagedpartial;
221 static LDAPControl *c = NULL;
222 static int nctrls = 0;
223 static int save_nctrls = 0;
231 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
232 if ( tmpc == NULL ) {
235 _("unable to make room for control; out of memory?\n"));
248 if (*LDAP_DIRSEP != '/') {
249 for (p = url; *p; p++) {
250 if (*p == *LDAP_DIRSEP)
257 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
258 "Cd:D:e:f:h:H:IMnO:o:p:P:QR:U:vVw:WxX:y:Y:Z";
261 handle_private_option( int i )
266 case 'a': /* set alias deref option */
267 if ( strcasecmp( optarg, "never" ) == 0 ) {
268 deref = LDAP_DEREF_NEVER;
269 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
270 deref = LDAP_DEREF_SEARCHING;
271 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
272 deref = LDAP_DEREF_FINDING;
273 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
274 deref = LDAP_DEREF_ALWAYS;
277 _("alias deref should be never, search, find, or always\n") );
281 case 'A': /* retrieve attribute names only -- no values */
284 case 'b': /* search base */
285 base = ber_strdup( optarg );
287 case 'E': /* search extensions */
288 if( protocol == LDAP_VERSION2 ) {
289 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
291 exit( EXIT_FAILURE );
294 /* should be extended to support comma separated list of
295 * [!]key[=value] parameters, e.g. -E !foo,bar=567
300 if( optarg[0] == '!' ) {
305 control = ber_strdup( optarg );
306 if ( (cvalue = strchr( control, '=' )) != NULL ) {
310 if ( strcasecmp( control, "mv" ) == 0 ) {
311 /* ValuesReturnFilter control */
312 if( valuesReturnFilter ) {
314 _("ValuesReturnFilter previously specified\n"));
315 exit( EXIT_FAILURE );
317 valuesReturnFilter= 1 + crit;
319 if ( cvalue == NULL ) {
321 _("missing filter in ValuesReturnFilter control\n"));
322 exit( EXIT_FAILURE );
326 protocol = LDAP_VERSION3;
328 } else if ( strcasecmp( control, "pr" ) == 0 ) {
330 /* PagedResults control */
331 if ( pagedResults != 0 ) {
333 _("PagedResultsControl previously specified\n") );
334 exit( EXIT_FAILURE );
337 if( cvalue != NULL ) {
340 promptp = strchr( cvalue, '/' );
341 if ( promptp != NULL ) {
343 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
345 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
349 _("Invalid value for PagedResultsControl,"
350 " %s/%s.\n"), cvalue, promptp );
351 exit( EXIT_FAILURE );
354 num = sscanf( cvalue, "%d", &tmp );
357 _("Invalid value for PagedResultsControl, %s.\n"),
359 exit( EXIT_FAILURE );
362 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
363 exit( EXIT_FAILURE );
365 pageSize = (ber_int_t) tmp;
366 pagedResults = 1 + crit;
368 #ifdef LDAP_CONTROL_DONTUSECOPY
369 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
372 _("dontUseCopy control previously specified\n"));
373 exit( EXIT_FAILURE );
375 if( cvalue != NULL ) {
377 _("dontUseCopy: no control value expected\n") );
382 _("dontUseCopy: critical flag required\n") );
386 dontUseCopy = 1 + crit;
388 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
391 _("domainScope control previously specified\n"));
392 exit( EXIT_FAILURE );
394 if( cvalue != NULL ) {
396 _("domainScope: no control value expected\n") );
400 domainScope = 1 + crit;
402 } else if ( strcasecmp( control, "sss" ) == 0 ) {
406 _("server side sorting control previously specified\n"));
407 exit( EXIT_FAILURE );
409 if( cvalue == NULL ) {
411 _("missing specification of sss control\n") );
412 exit( EXIT_FAILURE );
415 while (keyp = strchr(keyp, '/')) {
418 if ( ldap_create_sort_keylist( &sss_keys, cvalue )) {
420 _("server side sorting control value \"%s\" invalid\n"),
422 exit( EXIT_FAILURE );
427 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
430 _("subentries control previously specified\n"));
431 exit( EXIT_FAILURE );
433 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
435 } else if ( strcasecmp( cvalue, "false") == 0 ) {
439 _("subentries control value \"%s\" invalid\n"),
441 exit( EXIT_FAILURE );
443 if( crit ) subentries *= -1;
445 } else if ( strcasecmp( control, "sync" ) == 0 ) {
449 fprintf( stderr, _("sync control previously specified\n") );
450 exit( EXIT_FAILURE );
452 if ( cvalue == NULL ) {
453 fprintf( stderr, _("missing specification of sync control\n"));
454 exit( EXIT_FAILURE );
456 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
457 ldapsync = LDAP_SYNC_REFRESH_ONLY;
458 cookiep = strchr( cvalue, '/' );
459 if ( cookiep != NULL ) {
461 if ( *cookiep != '\0' ) {
462 ber_str2bv( cookiep, 0, 0, &sync_cookie );
465 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
466 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
467 cookiep = strchr( cvalue, '/' );
468 if ( cookiep != NULL ) {
472 slimitp = strchr( cvalue, '/' );
473 if ( slimitp != NULL ) {
476 if ( cookiep != NULL && *cookiep != '\0' )
477 ber_str2bv( cookiep, 0, 0, &sync_cookie );
478 if ( slimitp != NULL && *slimitp != '\0' ) {
479 ival = strtol( slimitp, &next, 10 );
480 if ( next == NULL || next[0] != '\0' ) {
481 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
482 exit( EXIT_FAILURE );
487 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
489 exit( EXIT_FAILURE );
491 if ( crit ) ldapsync *= -1;
493 } else if ( tool_is_oid( control ) ) {
495 exit( EXIT_FAILURE );
499 c[ nctrls - 1 ].ldctl_oid = control;
502 if ( cvalue == NULL ) {
503 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
504 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
506 } else if ( cvalue[ 0 ] == ':' ) {
514 * to use ldif_parse_line2() */
516 ldif_parse_line2( &cvalue[ -2 ], &type,
521 c[ nctrls - 1 ].ldctl_value = value;
524 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
529 c[ nctrls - 1 ].ldctl_iscritical = crit;
532 fprintf( stderr, _("Invalid search extension name: %s\n"),
537 case 'F': /* uri prefix */
538 if( urlpre ) free( urlpre );
539 urlpre = strdup( optarg );
541 case 'l': /* time limit */
542 if ( strcasecmp( optarg, "none" ) == 0 ) {
545 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
546 timelimit = LDAP_MAXINT;
549 ival = strtol( optarg, &next, 10 );
550 if ( next == NULL || next[0] != '\0' ) {
552 _("Unable to parse time limit \"%s\"\n"), optarg );
553 exit( EXIT_FAILURE );
557 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
558 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
560 exit( EXIT_FAILURE );
563 case 'L': /* print entries in LDIF format */
566 case 's': /* search scope */
567 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
568 scope = LDAP_SCOPE_BASE;
569 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
570 scope = LDAP_SCOPE_ONELEVEL;
571 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
572 || ( strcasecmp( optarg, "children" ) == 0 ))
574 scope = LDAP_SCOPE_SUBORDINATE;
575 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
576 scope = LDAP_SCOPE_SUBTREE;
578 fprintf( stderr, _("scope should be base, one, or sub\n") );
582 case 'S': /* sort attribute */
583 sortattr = strdup( optarg );
585 case 't': /* write attribute values to TMPDIR files */
588 case 'T': /* tmpdir */
589 if( tmpdir ) free( tmpdir );
590 tmpdir = strdup( optarg );
592 case 'u': /* include UFN */
595 case 'z': /* size limit */
596 if ( strcasecmp( optarg, "none" ) == 0 ) {
599 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
600 sizelimit = LDAP_MAXINT;
603 ival = strtol( optarg, &next, 10 );
604 if ( next == NULL || next[0] != '\0' ) {
606 _("Unable to parse size limit \"%s\"\n"), optarg );
607 exit( EXIT_FAILURE );
611 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
612 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
614 exit( EXIT_FAILURE );
625 private_conn_setup( LDAP *ld )
628 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
629 != LDAP_OPT_SUCCESS )
631 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
632 exit( EXIT_FAILURE );
635 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
636 != LDAP_OPT_SUCCESS )
639 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
640 exit( EXIT_FAILURE );
643 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
644 != LDAP_OPT_SUCCESS )
647 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
648 exit( EXIT_FAILURE );
653 main( int argc, char **argv )
655 char *filtpattern, **attrs = NULL, line[BUFSIZ];
657 int rc, rc1, i, first;
659 BerElement *seber = NULL, *vrber = NULL;
661 BerElement *syncber = NULL;
662 struct berval *syncbvalp = NULL;
665 tool_init( TOOL_SEARCH );
667 npagedresponses = npagedentries = npagedreferences =
668 npagedextended = npagedpartial = 0;
670 prog = lutil_progname( "ldapsearch", argc, argv );
672 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
673 (def_tmpdir = getenv("TMP")) == NULL &&
674 (def_tmpdir = getenv("TEMP")) == NULL )
676 def_tmpdir = LDAP_TMPDIR;
680 def_tmpdir = LDAP_TMPDIR;
682 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
684 if( def_urlpre == NULL ) {
689 sprintf( def_urlpre, "file:///%s/",
690 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
692 urlize( def_urlpre );
694 tool_args( argc, argv );
696 if (( argc - optind < 1 ) ||
697 ( *argv[optind] != '(' /*')'*/ &&
698 ( strchr( argv[optind], '=' ) == NULL ) ) )
700 filtpattern = "(objectclass=*)";
702 filtpattern = argv[optind++];
705 if ( argv[optind] != NULL ) {
706 attrs = &argv[optind];
709 if ( infile != NULL ) {
712 if ( infile[0] == '-' && infile[1] == '\0' ) {
714 } else if (( fp = fopen( infile, "r" )) == NULL ) {
719 for( i=0 ; filtpattern[i] ; i++ ) {
720 if( filtpattern[i] == '%' ) {
722 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
729 if( filtpattern[i+1] != 's' ) {
730 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
738 if ( tmpdir == NULL ) {
741 if ( urlpre == NULL )
745 if( urlpre == NULL ) {
746 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
748 if( urlpre == NULL ) {
753 sprintf( urlpre, "file:///%s/",
754 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
762 ld = tool_conn_setup( 0, &private_conn_setup );
764 if ( pw_file || want_bindpw ) {
766 rc = lutil_get_filed_password( pw_file, &passwd );
767 if( rc ) return EXIT_FAILURE;
769 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
770 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
777 save_nctrls = nctrls;
780 #ifdef LDAP_CONTROL_DONTUSECOPY
788 || valuesReturnFilter )
791 #ifdef LDAP_CONTROL_DONTUSECOPY
797 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
798 c[i].ldctl_value.bv_val = NULL;
799 c[i].ldctl_value.bv_len = 0;
800 c[i].ldctl_iscritical = dontUseCopy > 1;
810 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
811 c[i].ldctl_value.bv_val = NULL;
812 c[i].ldctl_value.bv_len = 0;
813 c[i].ldctl_iscritical = domainScope > 1;
822 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
826 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
828 ber_free( seber, 1 );
829 fprintf( stderr, _("Subentries control encoding error!\n") );
833 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
837 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
838 c[i].ldctl_iscritical = subentries < 1;
847 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
851 if ( sync_cookie.bv_len == 0 ) {
852 err = ber_printf( syncber, "{e}", abs(ldapsync) );
854 err = ber_printf( syncber, "{eO}", abs(ldapsync),
858 if ( err == LBER_ERROR ) {
859 ber_free( syncber, 1 );
860 fprintf( stderr, _("ldap sync control encoding error!\n") );
864 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
868 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
869 c[i].ldctl_value = (*syncbvalp);
870 c[i].ldctl_iscritical = ldapsync < 0;
874 if ( valuesReturnFilter ) {
879 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
883 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
884 ber_free( vrber, 1 );
885 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
889 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
893 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
894 c[i].ldctl_iscritical = valuesReturnFilter > 1;
898 if ( pagedResults ) {
903 if ( ldap_create_page_control_value( ld,
904 pageSize, &pr_cookie, &c[i].ldctl_value ) )
909 if ( pr_cookie.bv_val != NULL ) {
910 ber_memfree( pr_cookie.bv_val );
911 pr_cookie.bv_val = NULL;
912 pr_cookie.bv_len = 0;
915 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
916 c[i].ldctl_iscritical = pagedResults > 1;
925 if ( ldap_create_sort_control_value( ld,
926 sss_keys, &c[i].ldctl_value ) )
931 c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
932 c[i].ldctl_iscritical = sss > 1;
937 tool_server_controls( ld, c, i );
939 ber_free( seber, 1 );
940 ber_free( vrber, 1 );
942 /* step back to the original number of controls, so that
943 * those set while parsing args are preserved */
944 nctrls = save_nctrls;
947 fprintf( stderr, _("filter%s: %s\nrequesting: "),
948 infile != NULL ? _(" pattern") : "",
951 if ( attrs == NULL ) {
952 fprintf( stderr, _("All userApplication attributes") );
954 for ( i = 0; attrs[ i ] != NULL; ++i ) {
955 fprintf( stderr, "%s ", attrs[ i ] );
958 fprintf( stderr, "\n" );
962 printf( _("# extended LDIF\n") );
963 } else if ( ldif < 3 ) {
964 printf( _("version: %d\n\n"), 1 );
968 char *realbase = base;
970 if ( realbase == NULL ) {
971 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
975 printf(_("# LDAPv%d\n"), protocol);
976 printf(_("# base <%s>%s with scope %s\n"),
977 realbase ? realbase : "",
978 ( realbase == NULL || realbase != base ) ? " (default)" : "",
979 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
980 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
981 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
983 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
985 printf(_("# requesting: "));
987 if ( attrs == NULL ) {
990 for ( i = 0; attrs[ i ] != NULL; ++i ) {
991 printf( "%s ", attrs[ i ] );
996 printf(_("\n# with manageDSAit %scontrol"),
997 manageDSAit > 1 ? _("critical ") : "" );
1000 printf(_("\n# with noop %scontrol"),
1001 noop > 1 ? _("critical ") : "" );
1004 printf(_("\n# with subentries %scontrol: %s"),
1005 subentries < 0 ? _("critical ") : "",
1006 abs(subentries) == 1 ? "false" : "true" );
1008 if ( valuesReturnFilter ) {
1009 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1010 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1012 if ( pagedResults ) {
1013 printf(_("\n# with pagedResults %scontrol: size=%d"),
1014 (pagedResults > 1) ? _("critical ") : "",
1018 printf(_("\n# with server side sorting %scontrol"),
1019 sss > 1 ? _("critical ") : "" );
1022 printf( _("\n#\n\n") );
1024 if ( realbase && realbase != base ) {
1025 ldap_memfree( realbase );
1029 if ( infile == NULL ) {
1030 rc = dosearch( ld, base, scope, NULL, filtpattern,
1031 attrs, attrsonly, NULL, NULL, NULL, -1 );
1036 while ( fgets( line, sizeof( line ), fp ) != NULL ) {
1037 line[ strlen( line ) - 1 ] = '\0';
1043 rc1 = dosearch( ld, base, scope, filtpattern, line,
1044 attrs, attrsonly, NULL, NULL, NULL, -1 );
1052 if ( fp != stdin ) {
1057 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1059 int i, moreEntries, tmpSize;
1061 /* Loop to get the next pages when
1062 * enter is pressed on the terminal.
1064 if ( pagePrompt != 0 ) {
1065 if ( entriesLeft > 0 ) {
1066 printf( _("Estimate entries: %d\n"), entriesLeft );
1068 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1071 moreEntries = getchar();
1072 while ( moreEntries != EOF && moreEntries != '\n' ) {
1073 if ( i < (int)sizeof(buf) - 1 ) {
1074 buf[i] = moreEntries;
1077 moreEntries = getchar();
1081 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1082 int num = sscanf( buf, "%d", &tmpSize );
1085 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1086 return EXIT_FAILURE;
1089 pageSize = (ber_int_t)tmpSize;
1098 if ( base != NULL ) {
1099 ber_memfree( base );
1101 if ( control != NULL ) {
1102 ber_memfree( control );
1104 if ( sss_keys != NULL ) {
1105 ldap_free_sort_keylist( sss_keys );
1109 for ( ; save_nctrls-- > 0; ) {
1110 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1120 static int dosearch(
1128 LDAPControl **sctrls,
1129 LDAPControl **cctrls,
1130 struct timeval *timeout,
1140 LDAPMessage *res, *msg;
1142 char *retoid = NULL;
1143 struct berval *retdata = NULL;
1144 int nresponses_psearch = -1;
1145 int cancel_msgid = -1;
1147 if( filtpatt != NULL ) {
1148 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1;
1149 filter = malloc( max_fsize );
1150 if( filter == NULL ) {
1152 return EXIT_FAILURE;
1155 if( snprintf( filter, max_fsize, filtpatt, value ) >= max_fsize ) {
1156 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1158 return EXIT_FAILURE;
1162 fprintf( stderr, _("filter: %s\n"), filter );
1166 printf( _("#\n# filter: %s\n#\n"), filter );
1174 if ( filtpatt != NULL ) {
1177 return LDAP_SUCCESS;
1180 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1181 sctrls, cctrls, timeout, sizelimit, &msgid );
1183 if ( filtpatt != NULL ) {
1187 if( rc != LDAP_SUCCESS ) {
1188 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1189 prog, ldap_err2string( rc ), rc );
1193 nresponses = nentries = nreferences = nextended = npartial = 0;
1197 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1198 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1201 rc = tool_check_abandon( ld, msgid );
1207 (void) ldap_sort_entries( ld, &res,
1208 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1211 for ( msg = ldap_first_message( ld, res );
1213 msg = ldap_next_message( ld, msg ) )
1215 if ( nresponses++ ) putchar('\n');
1216 if ( nresponses_psearch >= 0 )
1217 nresponses_psearch++;
1219 switch( ldap_msgtype( msg ) ) {
1220 case LDAP_RES_SEARCH_ENTRY:
1222 print_entry( ld, msg, attrsonly );
1225 case LDAP_RES_SEARCH_REFERENCE:
1227 print_reference( ld, msg );
1230 case LDAP_RES_EXTENDED:
1232 print_extended( ld, msg );
1234 if ( ldap_msgid( msg ) == 0 ) {
1235 /* unsolicited extended operation */
1239 if ( cancel_msgid != -1 &&
1240 cancel_msgid == ldap_msgid( msg ) ) {
1241 printf(_("Cancelled \n"));
1242 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1247 case LDAP_RES_SEARCH_RESULT:
1248 /* pagedResults stuff is dealt with
1249 * in tool_print_ctrls(), called by
1250 * print_results(). */
1251 rc = print_result( ld, msg, 1 );
1252 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1258 case LDAP_RES_INTERMEDIATE:
1260 ldap_parse_intermediate( ld, msg,
1261 &retoid, &retdata, NULL, 0 );
1263 nresponses_psearch = 0;
1265 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1266 printf(_("SyncInfo Received\n"));
1267 ldap_memfree( retoid );
1268 ber_bvfree( retdata );
1272 print_partial( ld, msg );
1273 ldap_memfree( retoid );
1274 ber_bvfree( retdata );
1278 if ( ldapsync && sync_slimit != -1 &&
1279 nresponses_psearch >= sync_slimit ) {
1280 BerElement *msgidber = NULL;
1281 struct berval *msgidvalp = NULL;
1282 msgidber = ber_alloc_t(LBER_USE_DER);
1283 ber_printf(msgidber, "{i}", msgid);
1284 ber_flatten(msgidber, &msgidvalp);
1285 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1286 msgidvalp, NULL, NULL, &cancel_msgid);
1287 nresponses_psearch = -1;
1291 ldap_msgfree( res );
1296 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1300 ldap_msgfree( res );
1302 if ( pagedResults ) {
1303 npagedresponses += nresponses;
1304 npagedentries += nentries;
1305 npagedextended += nextended;
1306 npagedpartial += npartial;
1307 npagedreferences += nreferences;
1308 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1309 printf( _("\n# numResponses: %d\n"), npagedresponses );
1310 if( npagedentries ) {
1311 printf( _("# numEntries: %d\n"), npagedentries );
1313 if( npagedextended ) {
1314 printf( _("# numExtended: %d\n"), npagedextended );
1316 if( npagedpartial ) {
1317 printf( _("# numPartial: %d\n"), npagedpartial );
1319 if( npagedreferences ) {
1320 printf( _("# numReferences: %d\n"), npagedreferences );
1323 } else if ( ldif < 2 ) {
1324 printf( _("\n# numResponses: %d\n"), nresponses );
1325 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1326 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1327 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1328 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1334 /* This is the proposed new way of doing things.
1335 * It is more efficient, but the API is non-standard.
1344 char tmpfname[ 256 ];
1347 BerElement *ber = NULL;
1348 struct berval bv, *bvals, **bvp = &bvals;
1349 LDAPControl **ctrls = NULL;
1352 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1355 ufn = ldap_dn2ufn( bv.bv_val );
1356 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1358 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1360 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1361 if( rc != LDAP_SUCCESS ) {
1362 fprintf(stderr, _("print_entry: %d\n"), rc );
1363 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1364 exit( EXIT_FAILURE );
1368 tool_print_ctrls( ld, ctrls );
1369 ldap_controls_free( ctrls );
1374 ufn = ldap_dn2ufn( bv.bv_val );
1376 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1379 if( ufn != NULL ) ldap_memfree( ufn );
1381 if ( attrsonly ) bvp = NULL;
1383 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1385 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1387 if (bv.bv_val == NULL) break;
1390 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1392 } else if ( bvals ) {
1393 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1394 if ( vals2tmp > 1 || ( vals2tmp &&
1395 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1398 /* write value to file */
1399 snprintf( tmpfname, sizeof tmpfname,
1400 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1401 tmpdir, bv.bv_val );
1404 tmpfd = mkstemp( tmpfname );
1411 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1416 if ( fwrite( bvals[ i ].bv_val,
1417 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1426 snprintf( url, sizeof url, "%s%s", urlpre,
1427 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1430 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1433 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1434 bvals[ i ].bv_val, bvals[ i ].bv_len );
1437 ber_memfree( bvals );
1446 static void print_reference(
1448 LDAPMessage *reference )
1452 LDAPControl **ctrls;
1455 printf(_("# search reference\n"));
1458 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1460 if( rc != LDAP_SUCCESS ) {
1461 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1462 exit( EXIT_FAILURE );
1467 for( i=0; refs[i] != NULL; i++ ) {
1468 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1469 "ref", refs[i], strlen(refs[i]) );
1471 ber_memvfree( (void **) refs );
1475 tool_print_ctrls( ld, ctrls );
1476 ldap_controls_free( ctrls );
1480 static void print_extended(
1482 LDAPMessage *extended )
1485 char *retoid = NULL;
1486 struct berval *retdata = NULL;
1489 printf(_("# extended result response\n"));
1492 rc = ldap_parse_extended_result( ld, extended,
1493 &retoid, &retdata, 0 );
1495 if( rc != LDAP_SUCCESS ) {
1496 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1497 exit( EXIT_FAILURE );
1501 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1502 "extended", retoid, retoid ? strlen(retoid) : 0 );
1504 ber_memfree( retoid );
1508 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1509 "data", retdata->bv_val, retdata->bv_len );
1511 ber_bvfree( retdata );
1514 print_result( ld, extended, 0 );
1517 static void print_partial(
1519 LDAPMessage *partial )
1522 char *retoid = NULL;
1523 struct berval *retdata = NULL;
1524 LDAPControl **ctrls = NULL;
1527 printf(_("# extended partial response\n"));
1530 rc = ldap_parse_intermediate( ld, partial,
1531 &retoid, &retdata, &ctrls, 0 );
1533 if( rc != LDAP_SUCCESS ) {
1534 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1535 exit( EXIT_FAILURE );
1539 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1540 "partial", retoid, retoid ? strlen(retoid) : 0 );
1543 ber_memfree( retoid );
1547 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1548 "data", retdata->bv_val, retdata->bv_len );
1551 ber_bvfree( retdata );
1555 tool_print_ctrls( ld, ctrls );
1556 ldap_controls_free( ctrls );
1560 static int print_result(
1562 LDAPMessage *result, int search )
1566 char *matcheddn = NULL;
1569 LDAPControl **ctrls = NULL;
1573 printf(_("# search result\n"));
1576 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1580 rc = ldap_parse_result( ld, result,
1581 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1583 if( rc != LDAP_SUCCESS ) {
1584 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1585 exit( EXIT_FAILURE );
1590 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1592 } else if ( err != LDAP_SUCCESS ) {
1593 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1599 tool_write_ldif( LDIF_PUT_VALUE,
1600 "matchedDN", matcheddn, strlen(matcheddn) );
1602 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1606 ber_memfree( matcheddn );
1612 if ( err == LDAP_PARTIAL_RESULTS ) {
1615 for ( line = text; line != NULL; ) {
1616 char *next = strchr( line, '\n' );
1618 tool_write_ldif( LDIF_PUT_TEXT,
1620 next ? next - line : strlen( line ) );
1622 line = next ? next + 1 : NULL;
1626 tool_write_ldif( LDIF_PUT_TEXT, "text",
1627 text, strlen(text) );
1630 fprintf( stderr, _("Additional information: %s\n"), text );
1634 ber_memfree( text );
1639 for( i=0; refs[i] != NULL; i++ ) {
1641 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1643 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1647 ber_memvfree( (void **) refs );
1650 pr_morePagedResults = 0;
1653 tool_print_ctrls( ld, ctrls );
1654 ldap_controls_free( ctrls );