1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2005 The OpenLDAP Foundation.
6 * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7 * Portions Copyright 1998-2001 Net Boolean Incorporated.
8 * Portions Copyright 2001-2003 IBM Corporation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms are permitted
23 * provided that this notice is preserved and that due credit is given
24 * to the University of Michigan at Ann Arbor. The name of the
25 * University may not be used to endorse or promote products derived
26 * from this software without specific prior written permission. This
27 * software is provided ``as is'' without express or implied warranty.
30 * This work was originally developed by the University of Michigan
31 * (as part of U-MICH LDAP). Additional significant contributors
43 #include <ac/stdlib.h>
46 #include <ac/string.h>
47 #include <ac/unistd.h>
51 #include <ac/signal.h>
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
67 #include "lutil_ldap.h"
68 #include "ldap_defaults.h"
76 * NOTE: we use this deprecated function only because
77 * we want ldapsearch to provide some client-side sorting
81 typedef int (LDAP_SORT_AD_CMP_PROC) LDAP_P(( /* deprecated */
82 LDAP_CONST char *left,
83 LDAP_CONST char *right ));
85 LDAP_F( int ) /* deprecated */
86 ldap_sort_entries LDAP_P(( LDAP *ld,
88 LDAP_CONST char *attr,
89 LDAP_SORT_AD_CMP_PROC *cmp ));
92 static int scope = LDAP_SCOPE_SUBTREE;
93 static int deref = -1;
95 static int timelimit = -1;
96 static int sizelimit = -1;
98 static char *def_tmpdir;
99 static char *def_urlpre;
101 #if defined(__CYGWIN__) || defined(__MINGW32__)
102 /* Turn off commandline globbing, otherwise you cannot search for
111 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
112 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
113 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
114 fprintf( stderr, _(" which may include:\n"));
115 fprintf( stderr, _(" 1.1 no attributes\n"));
116 fprintf( stderr, _(" * all user attributes\n"));
117 fprintf( stderr, _(" + all operational attributes\n"));
120 fprintf( stderr, _("Search options:\n"));
121 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
122 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
123 fprintf( stderr, _(" -b basedn base dn for search\n"));
124 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
125 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
126 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
128 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
129 #ifdef LDAP_CONTROL_PAGEDRESULTS
130 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
132 #ifdef LDAP_CONTROL_SUBENTRIES
133 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
135 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
136 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
137 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
138 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
139 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
140 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
141 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
142 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
143 fprintf( stderr, _(" and version\n"));
144 #ifdef LDAP_SCOPE_SUBORDINATE
145 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
146 #else /* ! LDAP_SCOPE_SUBORDINATE */
147 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
148 #endif /* ! LDAP_SCOPE_SUBORDINATE */
149 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
150 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
151 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
152 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
153 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
154 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
156 exit( EXIT_FAILURE );
159 static void print_entry LDAP_P((
164 static void print_reference(
166 LDAPMessage *reference );
168 static void print_extended(
170 LDAPMessage *extended );
172 static void print_partial(
174 LDAPMessage *partial );
176 static int print_result(
181 static void print_ctrls(
182 LDAPControl **ctrls );
184 static int write_ldif LDAP_P((
190 static int dosearch LDAP_P((
198 LDAPControl **sctrls,
199 LDAPControl **cctrls,
200 struct timeval *timeout,
203 static char *tmpdir = NULL;
204 static char *urlpre = NULL;
205 static char *base = NULL;
206 static char *sortattr = NULL;
207 static int includeufn, vals2tmp = 0, ldif = 0;
209 static int subentries = 0, valuesReturnFilter = 0;
210 static char *vrFilter = NULL;
212 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
213 static int domainScope = 0;
216 static int ldapsync = 0;
217 static struct berval sync_cookie = { 0, NULL };
218 static int sync_slimit = -1;
220 #ifdef LDAP_CONTROL_PAGEDRESULTS
221 static int pagedResults = 0;
222 static int pagePrompt = 1;
223 static ber_int_t pageSize = 0;
224 static ber_int_t entriesLeft = 0;
225 static ber_int_t morePagedResults = 1;
226 static struct berval page_cookie = { 0, NULL };
227 static int npagedresponses;
228 static int npagedentries;
229 static int npagedreferences;
230 static int npagedextended;
231 static int npagedpartial;
233 static LDAPControl *c = NULL;
234 static int nctrls = 0;
235 static int save_nctrls = 0;
243 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
244 if ( tmpc == NULL ) {
247 _("unable to make room for control; out of memory?\n"));
256 is_oid( const char *s )
260 if ( !isdigit( s[ 0 ] ) ) {
264 for ( ; s[ 0 ]; s++ ) {
265 if ( s[ 0 ] == '.' ) {
266 if ( s[ 1 ] == '\0' ) {
273 if ( !isdigit( s[ 0 ] ) ) {
277 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
286 static int parse_page_control(
289 struct berval *cookie );
297 if (*LDAP_DIRSEP != '/') {
298 for (p = url; *p; p++) {
299 if (*p == *LDAP_DIRSEP)
306 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
307 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
310 handle_private_option( int i )
313 char *control, *cvalue, *next;
315 case 'a': /* set alias deref option */
316 if ( strcasecmp( optarg, "never" ) == 0 ) {
317 deref = LDAP_DEREF_NEVER;
318 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
319 deref = LDAP_DEREF_SEARCHING;
320 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
321 deref = LDAP_DEREF_FINDING;
322 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
323 deref = LDAP_DEREF_ALWAYS;
326 _("alias deref should be never, search, find, or always\n") );
330 case 'A': /* retrieve attribute names only -- no values */
333 case 'b': /* search base */
334 base = ber_strdup( optarg );
336 case 'E': /* search extensions */
337 if( protocol == LDAP_VERSION2 ) {
338 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
340 exit( EXIT_FAILURE );
343 /* should be extended to support comma separated list of
344 * [!]key[=value] parameters, e.g. -E !foo,bar=567
349 if( optarg[0] == '!' ) {
354 control = ber_strdup( optarg );
355 if ( (cvalue = strchr( control, '=' )) != NULL ) {
359 if ( strcasecmp( control, "mv" ) == 0 ) {
360 /* ValuesReturnFilter control */
361 if( valuesReturnFilter ) {
363 _("ValuesReturnFilter previously specified\n"));
364 exit( EXIT_FAILURE );
366 valuesReturnFilter= 1 + crit;
368 if ( cvalue == NULL ) {
370 _("missing filter in ValuesReturnFilter control\n"));
371 exit( EXIT_FAILURE );
375 protocol = LDAP_VERSION3;
377 #ifdef LDAP_CONTROL_PAGEDRESULTS
378 } else if ( strcasecmp( control, "pr" ) == 0 ) {
380 /* PagedResults control */
381 if ( pagedResults != 0 ) {
383 _("PagedResultsControl previously specified\n") );
384 exit( EXIT_FAILURE );
387 if( cvalue != NULL ) {
390 promptp = strchr( cvalue, '/' );
391 if ( promptp != NULL ) {
393 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
395 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
399 _("Invalid value for PagedResultsControl,"
400 " %s/%s.\n"), cvalue, promptp );
401 exit( EXIT_FAILURE );
404 num = sscanf( cvalue, "%d", &tmp );
407 _("Invalid value for PagedResultsControl, %s.\n"),
409 exit( EXIT_FAILURE );
412 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
413 exit( EXIT_FAILURE );
415 pageSize = (ber_int_t) tmp;
416 pagedResults = 1 + crit;
419 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
420 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
423 _("domainScope control previously specified\n"));
424 exit( EXIT_FAILURE );
426 if( cvalue != NULL ) {
428 _("domainScope: no control value expected\n") );
432 domainScope = 1 + crit;
435 #ifdef LDAP_CONTROL_SUBENTRIES
436 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
439 _("subentries control previously specified\n"));
440 exit( EXIT_FAILURE );
442 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
444 } else if ( strcasecmp( cvalue, "false") == 0 ) {
448 _("subentries control value \"%s\" invalid\n"),
450 exit( EXIT_FAILURE );
452 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 } else if ( is_oid( control ) ) {
505 exit( EXIT_FAILURE );
509 c[ nctrls - 1 ].ldctl_oid = control;
512 if ( cvalue == NULL ) {
513 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
514 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
516 } else if ( cvalue[ 0 ] == ':' ) {
524 * to use ldif_parse_line2() */
526 ldif_parse_line2( &cvalue[ -2 ], &type,
531 c[ nctrls - 1 ].ldctl_value = value;
534 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
539 c[ nctrls - 1 ].ldctl_iscritical = crit;
542 fprintf( stderr, _("Invalid search extension name: %s\n"),
547 case 'F': /* uri prefix */
548 if( urlpre ) free( urlpre );
549 urlpre = strdup( optarg );
551 case 'l': /* time limit */
552 if ( strcasecmp( optarg, "none" ) == 0 ) {
555 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
556 timelimit = LDAP_MAXINT;
559 ival = strtol( optarg, &next, 10 );
560 if ( next == NULL || next[0] != '\0' ) {
562 _("Unable to parse time limit \"%s\"\n"), optarg );
563 exit( EXIT_FAILURE );
567 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
568 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
570 exit( EXIT_FAILURE );
573 case 'L': /* print entries in LDIF format */
576 case 's': /* search scope */
577 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
578 scope = LDAP_SCOPE_BASE;
579 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
580 scope = LDAP_SCOPE_ONELEVEL;
581 #ifdef LDAP_SCOPE_SUBORDINATE
582 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
583 || ( strcasecmp( optarg, "children" ) == 0 ))
585 scope = LDAP_SCOPE_SUBORDINATE;
587 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
588 scope = LDAP_SCOPE_SUBTREE;
590 fprintf( stderr, _("scope should be base, one, or sub\n") );
594 case 'S': /* sort attribute */
595 sortattr = strdup( optarg );
597 case 't': /* write attribute values to TMPDIR files */
600 case 'T': /* tmpdir */
601 if( tmpdir ) free( tmpdir );
602 tmpdir = strdup( optarg );
604 case 'u': /* include UFN */
607 case 'z': /* size limit */
608 if ( strcasecmp( optarg, "none" ) == 0 ) {
611 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
612 sizelimit = LDAP_MAXINT;
615 ival = strtol( optarg, &next, 10 );
616 if ( next == NULL || next[0] != '\0' ) {
618 _("Unable to parse size limit \"%s\"\n"), optarg );
619 exit( EXIT_FAILURE );
623 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
624 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
626 exit( EXIT_FAILURE );
637 private_conn_setup( LDAP *ld )
640 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
641 != LDAP_OPT_SUCCESS )
643 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
644 exit( EXIT_FAILURE );
647 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
648 != LDAP_OPT_SUCCESS )
651 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
652 exit( EXIT_FAILURE );
655 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
656 != LDAP_OPT_SUCCESS )
659 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
660 exit( EXIT_FAILURE );
665 main( int argc, char **argv )
667 char *filtpattern, **attrs = NULL, line[BUFSIZ];
671 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
673 BerElement *syncber = NULL;
674 struct berval *syncbvalp = NULL;
678 #ifdef LDAP_CONTROL_PAGEDRESULTS
679 npagedresponses = npagedentries = npagedreferences =
680 npagedextended = npagedpartial = 0;
683 prog = lutil_progname( "ldapsearch", argc, argv );
685 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
686 (def_tmpdir = getenv("TMP")) == NULL &&
687 (def_tmpdir = getenv("TEMP")) == NULL )
689 def_tmpdir = LDAP_TMPDIR;
693 def_tmpdir = LDAP_TMPDIR;
695 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
697 if( def_urlpre == NULL ) {
702 sprintf( def_urlpre, "file:///%s/",
703 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
705 urlize( def_urlpre );
707 tool_args( argc, argv );
709 if (( argc - optind < 1 ) ||
710 ( *argv[optind] != '(' /*')'*/ &&
711 ( strchr( argv[optind], '=' ) == NULL ) ) )
713 filtpattern = "(objectclass=*)";
715 filtpattern = argv[optind++];
718 if ( argv[optind] != NULL ) {
719 attrs = &argv[optind];
722 if ( infile != NULL ) {
723 if ( infile[0] == '-' && infile[1] == '\0' ) {
725 } else if (( fp = fopen( infile, "r" )) == NULL ) {
731 if ( tmpdir == NULL ) {
734 if ( urlpre == NULL )
738 if( urlpre == NULL ) {
739 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
741 if( urlpre == NULL ) {
746 sprintf( urlpre, "file:///%s/",
747 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
755 ld = tool_conn_setup( 0, &private_conn_setup );
757 if ( pw_file || want_bindpw ) {
759 rc = lutil_get_filed_password( pw_file, &passwd );
760 if( rc ) return EXIT_FAILURE;
762 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
763 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
770 if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
771 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
774 #ifdef LDAP_CONTROL_PAGEDRESULTS
777 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
779 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
781 || subentries || valuesReturnFilter )
785 save_nctrls = nctrls;
787 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
793 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
794 c[i].ldctl_value.bv_val = NULL;
795 c[i].ldctl_value.bv_len = 0;
796 c[i].ldctl_iscritical = domainScope > 1;
801 #ifdef LDAP_CONTROL_SUBENTRIES
807 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
811 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
813 ber_free( seber, 1 );
814 fprintf( stderr, _("Subentries control encoding error!\n") );
818 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
822 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
823 c[i].ldctl_iscritical = subentries < 1;
833 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
837 if ( sync_cookie.bv_len == 0 ) {
838 err = ber_printf( syncber, "{e}", abs(ldapsync) );
840 err = ber_printf( syncber, "{eO}", abs(ldapsync),
844 if ( err == LBER_ERROR ) {
845 ber_free( syncber, 1 );
846 fprintf( stderr, _("ldap sync control encoding error!\n") );
850 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
854 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
855 c[i].ldctl_value = (*syncbvalp);
856 c[i].ldctl_iscritical = ldapsync < 0;
860 if ( valuesReturnFilter ) {
865 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
869 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
870 ber_free( vrber, 1 );
871 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
875 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
879 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
880 c[i].ldctl_iscritical = valuesReturnFilter > 1;
884 #ifdef LDAP_CONTROL_PAGEDRESULTS
885 if ( pagedResults ) {
890 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
894 ber_printf( prber, "{iO}", pageSize, &page_cookie );
895 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
898 if ( page_cookie.bv_val != NULL ) {
899 ber_memfree( page_cookie.bv_val );
900 page_cookie.bv_val = NULL;
903 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
904 c[i].ldctl_iscritical = pagedResults > 1;
909 tool_server_controls( ld, c, i );
911 /* step back to the original number of controls, so that
912 * those set while parsing args are preserved */
913 nctrls = save_nctrls;
915 #ifdef LDAP_CONTROL_SUBENTRIES
916 ber_free( seber, 1 );
918 ber_free( vrber, 1 );
919 #ifdef LDAP_CONTROL_PAGEDRESULTS
920 ber_free( prber, 1 );
925 fprintf( stderr, _("filter%s: %s\nrequesting: "),
926 infile != NULL ? _(" pattern") : "",
929 if ( attrs == NULL ) {
930 fprintf( stderr, _("ALL") );
932 for ( i = 0; attrs[ i ] != NULL; ++i ) {
933 fprintf( stderr, "%s ", attrs[ i ] );
936 fprintf( stderr, "\n" );
940 printf( _("# extended LDIF\n") );
941 } else if ( ldif < 3 ) {
942 printf( _("version: %d\n\n"), 1 );
947 printf(_("# LDAPv%d\n"), protocol);
948 printf(_("# base <%s> with scope %s\n"),
950 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
951 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
952 #ifdef LDAP_SCOPE_SUBORDINATE
953 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
956 #ifdef LDAP_SCOPE_SUBORDINATE
960 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
962 printf(_("# requesting: "));
964 if ( attrs == NULL ) {
967 for ( i = 0; attrs[ i ] != NULL; ++i ) {
968 printf( "%s ", attrs[ i ] );
973 printf(_("\n# with manageDSAit %scontrol"),
974 manageDSAit > 1 ? _("critical ") : "" );
977 printf(_("\n# with noop %scontrol"),
978 noop > 1 ? _("critical ") : "" );
981 printf(_("\n# with subentries %scontrol: %s"),
982 subentries < 0 ? _("critical ") : "",
983 abs(subentries) == 1 ? "false" : "true" );
985 if ( valuesReturnFilter ) {
986 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
987 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
989 #ifdef LDAP_CONTROL_PAGEDRESULTS
990 if ( pagedResults ) {
991 printf(_("\n# with pagedResults %scontrol: size=%d"),
992 (pagedResults > 1) ? _("critical ") : "",
997 printf( _("\n#\n\n") );
1000 if ( infile == NULL ) {
1001 rc = dosearch( ld, base, scope, NULL, filtpattern,
1002 attrs, attrsonly, NULL, NULL, NULL, -1 );
1007 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
1008 line[ strlen( line ) - 1 ] = '\0';
1014 rc = dosearch( ld, base, scope, filtpattern, line,
1015 attrs, attrsonly, NULL, NULL, NULL, -1 );
1017 if ( fp != stdin ) {
1022 #ifdef LDAP_CONTROL_PAGEDRESULTS
1023 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
1025 int i, moreEntries, tmpSize;
1027 /* Loop to get the next pages when
1028 * enter is pressed on the terminal.
1030 if ( pagePrompt != 0 ) {
1031 if ( entriesLeft > 0 ) {
1032 printf( _("Estimate entries: %d\n"), entriesLeft );
1034 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1037 moreEntries = getchar();
1038 while ( moreEntries != EOF && moreEntries != '\n' ) {
1039 if ( i < (int)sizeof(buf) - 1 ) {
1040 buf[i] = moreEntries;
1043 moreEntries = getchar();
1047 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1048 int num = sscanf( buf, "%d", &tmpSize );
1050 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
1051 return EXIT_FAILURE;
1054 pageSize = (ber_int_t)tmpSize;
1066 for ( ; save_nctrls-- > 0; ) {
1067 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1077 static int dosearch(
1085 LDAPControl **sctrls,
1086 LDAPControl **cctrls,
1087 struct timeval *timeout,
1097 LDAPMessage *res, *msg;
1099 char *retoid = NULL;
1100 struct berval *retdata = NULL;
1101 int nresponses_psearch = -1;
1102 int cancel_msgid = -1;
1104 if( filtpatt != NULL ) {
1105 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1106 if( filter == NULL ) {
1108 return EXIT_FAILURE;
1111 sprintf( filter, filtpatt, value );
1114 fprintf( stderr, _("filter: %s\n"), filter );
1118 printf( _("#\n# filter: %s\n#\n"), filter );
1126 return LDAP_SUCCESS;
1129 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1130 sctrls, cctrls, timeout, sizelimit, &msgid );
1132 if ( filtpatt != NULL ) {
1136 if( rc != LDAP_SUCCESS ) {
1137 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1138 prog, ldap_err2string( rc ), rc );
1142 nresponses = nentries = nreferences = nextended = npartial = 0;
1146 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1147 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1150 rc = tool_check_abandon( ld, msgid );
1156 (void) ldap_sort_entries( ld, &res,
1157 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1160 for ( msg = ldap_first_message( ld, res );
1162 msg = ldap_next_message( ld, msg ) )
1164 if ( nresponses++ ) putchar('\n');
1165 if ( nresponses_psearch >= 0 )
1166 nresponses_psearch++;
1168 switch( ldap_msgtype( msg ) ) {
1169 case LDAP_RES_SEARCH_ENTRY:
1171 print_entry( ld, msg, attrsonly );
1174 case LDAP_RES_SEARCH_REFERENCE:
1176 print_reference( ld, msg );
1179 case LDAP_RES_EXTENDED:
1181 print_extended( ld, msg );
1183 if( ldap_msgid( msg ) == 0 ) {
1184 /* unsolicited extended operation */
1188 if ( cancel_msgid != -1 &&
1189 cancel_msgid == ldap_msgid( msg ) ) {
1190 printf(_("Cancelled \n"));
1191 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1196 case LDAP_RES_SEARCH_RESULT:
1197 rc = print_result( ld, msg, 1 );
1198 #ifdef LDAP_CONTROL_PAGEDRESULTS
1199 if ( pageSize != 0 ) {
1200 if ( rc == LDAP_SUCCESS ) {
1201 rc = parse_page_control( ld, msg, &page_cookie );
1203 morePagedResults = 0;
1206 morePagedResults = 0;
1210 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1216 case LDAP_RES_INTERMEDIATE:
1218 ldap_parse_intermediate( ld, msg,
1219 &retoid, &retdata, NULL, 0 );
1221 nresponses_psearch = 0;
1223 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1224 printf(_("SyncInfo Received\n"));
1225 ldap_memfree( retoid );
1226 ber_bvfree( retdata );
1230 print_partial( ld, msg );
1231 ldap_memfree( retoid );
1232 ber_bvfree( retdata );
1236 if ( ldapsync && sync_slimit != -1 &&
1237 nresponses_psearch >= sync_slimit ) {
1238 BerElement *msgidber = NULL;
1239 struct berval *msgidvalp = NULL;
1240 msgidber = ber_alloc_t(LBER_USE_DER);
1241 ber_printf(msgidber, "{i}", msgid);
1242 ber_flatten(msgidber, &msgidvalp);
1243 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1244 msgidvalp, NULL, NULL, &cancel_msgid);
1245 nresponses_psearch = -1;
1249 ldap_msgfree( res );
1254 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1258 ldap_msgfree( res );
1259 #ifdef LDAP_CONTROL_PAGEDRESULTS
1260 if ( pagedResults ) {
1261 npagedresponses += nresponses;
1262 npagedentries += nentries;
1263 npagedextended += nextended;
1264 npagedpartial += npartial;
1265 npagedreferences += nreferences;
1266 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1267 printf( _("\n# numResponses: %d\n"), npagedresponses );
1268 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1269 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1270 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1271 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1276 printf( _("\n# numResponses: %d\n"), nresponses );
1277 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1278 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1279 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1280 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1286 /* This is the proposed new way of doing things.
1287 * It is more efficient, but the API is non-standard.
1296 char tmpfname[ 256 ];
1299 BerElement *ber = NULL;
1300 struct berval bv, *bvals, **bvp = &bvals;
1301 LDAPControl **ctrls = NULL;
1304 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1307 ufn = ldap_dn2ufn( bv.bv_val );
1308 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1310 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1312 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1313 if( rc != LDAP_SUCCESS ) {
1314 fprintf(stderr, _("print_entry: %d\n"), rc );
1315 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1316 exit( EXIT_FAILURE );
1320 print_ctrls( ctrls );
1321 ldap_controls_free( ctrls );
1326 ufn = ldap_dn2ufn( bv.bv_val );
1328 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1331 if( ufn != NULL ) ldap_memfree( ufn );
1333 if ( attrsonly ) bvp = NULL;
1335 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1337 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1339 if (bv.bv_val == NULL) break;
1342 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1344 } else if ( bvals ) {
1345 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1346 if ( vals2tmp > 1 || ( vals2tmp &&
1347 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1350 /* write value to file */
1351 snprintf( tmpfname, sizeof tmpfname,
1352 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1353 tmpdir, bv.bv_val );
1356 tmpfd = mkstemp( tmpfname );
1363 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1368 if ( fwrite( bvals[ i ].bv_val,
1369 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1378 snprintf( url, sizeof url, "%s%s", urlpre,
1379 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1382 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1385 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1386 bvals[ i ].bv_val, bvals[ i ].bv_len );
1389 ber_memfree( bvals );
1398 static void print_reference(
1400 LDAPMessage *reference )
1404 LDAPControl **ctrls;
1407 printf(_("# search reference\n"));
1410 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1412 if( rc != LDAP_SUCCESS ) {
1413 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1414 exit( EXIT_FAILURE );
1419 for( i=0; refs[i] != NULL; i++ ) {
1420 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1421 "ref", refs[i], strlen(refs[i]) );
1423 ber_memvfree( (void **) refs );
1427 print_ctrls( ctrls );
1428 ldap_controls_free( ctrls );
1432 static void print_extended(
1434 LDAPMessage *extended )
1437 char *retoid = NULL;
1438 struct berval *retdata = NULL;
1441 printf(_("# extended result response\n"));
1444 rc = ldap_parse_extended_result( ld, extended,
1445 &retoid, &retdata, 0 );
1447 if( rc != LDAP_SUCCESS ) {
1448 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1449 exit( EXIT_FAILURE );
1453 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1454 "extended", retoid, retoid ? strlen(retoid) : 0 );
1456 ber_memfree( retoid );
1460 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1461 "data", retdata->bv_val, retdata->bv_len );
1463 ber_bvfree( retdata );
1466 print_result( ld, extended, 0 );
1469 static void print_partial(
1471 LDAPMessage *partial )
1474 char *retoid = NULL;
1475 struct berval *retdata = NULL;
1476 LDAPControl **ctrls = NULL;
1479 printf(_("# extended partial response\n"));
1482 rc = ldap_parse_intermediate( ld, partial,
1483 &retoid, &retdata, &ctrls, 0 );
1485 if( rc != LDAP_SUCCESS ) {
1486 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1487 exit( EXIT_FAILURE );
1491 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1492 "partial", retoid, retoid ? strlen(retoid) : 0 );
1495 ber_memfree( retoid );
1499 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1500 "data", retdata->bv_val, retdata->bv_len );
1503 ber_bvfree( retdata );
1507 print_ctrls( ctrls );
1508 ldap_controls_free( ctrls );
1512 static int print_result(
1514 LDAPMessage *result, int search )
1518 char *matcheddn = NULL;
1521 LDAPControl **ctrls = NULL;
1525 printf(_("# search result\n"));
1528 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1532 rc = ldap_parse_result( ld, result,
1533 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1535 if( rc != LDAP_SUCCESS ) {
1536 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1537 exit( EXIT_FAILURE );
1542 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1544 } else if ( err != LDAP_SUCCESS ) {
1545 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1551 write_ldif( LDIF_PUT_VALUE,
1552 "matchedDN", matcheddn, strlen(matcheddn) );
1554 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1558 ber_memfree( matcheddn );
1564 write_ldif( LDIF_PUT_TEXT, "text",
1565 text, strlen(text) );
1567 fprintf( stderr, _("Additional information: %s\n"), text );
1571 ber_memfree( text );
1576 for( i=0; refs[i] != NULL; i++ ) {
1578 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1580 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1584 ber_memvfree( (void **) refs );
1588 print_ctrls( ctrls );
1589 ldap_controls_free( ctrls );
1595 static void print_ctrls(
1596 LDAPControl **ctrls )
1599 for(i=0; ctrls[i] != NULL; i++ ) {
1600 /* control: OID criticality base64value */
1601 struct berval *b64 = NULL;
1606 len += strlen( ctrls[i]->ldctl_oid );
1608 /* add enough for space after OID and the critical value itself */
1609 len += ctrls[i]->ldctl_iscritical
1610 ? sizeof("true") : sizeof("false");
1612 /* convert to base64 */
1613 if( ctrls[i]->ldctl_value.bv_len ) {
1614 b64 = ber_memalloc( sizeof(struct berval) );
1616 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1617 ctrls[i]->ldctl_value.bv_len ) + 1;
1618 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1620 b64->bv_len = lutil_b64_ntop(
1621 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1622 ctrls[i]->ldctl_value.bv_len,
1623 b64->bv_val, b64->bv_len );
1627 len += 1 + b64->bv_len;
1630 str = malloc( len + 1 );
1632 strcpy( str, ": " );
1636 strcat( str, ctrls[i]->ldctl_oid );
1637 strcat( str, ctrls[i]->ldctl_iscritical
1638 ? " true" : " false" );
1642 strcat(str, b64->bv_val );
1646 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1647 "control", str, len );
1656 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1660 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1664 fputs( ldif, stdout );
1665 ber_memfree( ldif );
1671 #ifdef LDAP_CONTROL_PAGEDRESULTS
1675 LDAPMessage *result,
1676 struct berval *cookie )
1680 LDAPControl **ctrl = NULL;
1681 LDAPControl *ctrlp = NULL;
1685 rc = ldap_parse_result( ld, result,
1686 &err, NULL, NULL, NULL, &ctrl, 0 );
1688 if( rc != LDAP_SUCCESS ) {
1689 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1690 exit( EXIT_FAILURE );
1693 if ( err != LDAP_SUCCESS ) {
1694 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1698 /* Parse the control value
1699 * searchResult ::= SEQUENCE {
1700 * size INTEGER (0..maxInt),
1701 * -- result set size estimate from server - unused
1702 * cookie OCTET STRING
1706 ber = ber_init( &ctrlp->ldctl_value );
1707 if ( ber == NULL ) {
1708 fprintf( stderr, _("Internal error.\n") );
1709 return EXIT_FAILURE;
1712 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1713 (void) ber_free( ber, 1 );
1715 if( tag == LBER_ERROR ) {
1717 _("Paged results response control could not be decoded.\n") );
1718 return EXIT_FAILURE;
1721 if( entriesLeft < 0 ) {
1723 _("Invalid entries estimate in paged results response.\n") );
1724 return EXIT_FAILURE;
1727 if ( cookie->bv_len == 0 ) {
1728 morePagedResults = 0;
1731 ldap_controls_free( ctrl );
1734 morePagedResults = 0;