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 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
137 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
138 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
139 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
140 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
141 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
142 fprintf( stderr, _(" and version\n"));
143 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
144 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
145 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
146 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
147 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
148 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
149 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
151 exit( EXIT_FAILURE );
154 static void print_entry LDAP_P((
159 static void print_reference(
161 LDAPMessage *reference );
163 static void print_extended(
165 LDAPMessage *extended );
167 static void print_partial(
169 LDAPMessage *partial );
171 static int print_result(
176 static int dosearch LDAP_P((
184 LDAPControl **sctrls,
185 LDAPControl **cctrls,
186 struct timeval *timeout,
189 static char *tmpdir = NULL;
190 static char *urlpre = NULL;
191 static char *base = NULL;
192 static char *sortattr = NULL;
193 static int includeufn, vals2tmp = 0;
195 static int subentries = 0, valuesReturnFilter = 0;
196 static char *vrFilter = NULL;
198 #ifdef LDAP_CONTROL_DONTUSECOPY
199 static int dontUseCopy = 0;
202 static int domainScope = 0;
205 static LDAPSortKey **sss_keys = NULL;
207 static int ldapsync = 0;
208 static struct berval sync_cookie = { 0, NULL };
209 static int sync_slimit = -1;
211 /* cookie and morePagedResults moved to common.c */
212 static int pagedResults = 0;
213 static int pagePrompt = 1;
214 static ber_int_t pageSize = 0;
215 static ber_int_t entriesLeft = 0;
216 static int npagedresponses;
217 static int npagedentries;
218 static int npagedreferences;
219 static int npagedextended;
220 static int npagedpartial;
222 static LDAPControl *c = NULL;
223 static int nctrls = 0;
224 static int save_nctrls = 0;
232 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
233 if ( tmpc == NULL ) {
236 _("unable to make room for control; out of memory?\n"));
249 if (*LDAP_DIRSEP != '/') {
250 for (p = url; *p; p++) {
251 if (*p == *LDAP_DIRSEP)
258 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
259 "Cd:D:e:f:h:H:IMnO:o:p:P:QR:U:vVw:WxX:y:Y:Z";
262 handle_private_option( int i )
267 case 'a': /* set alias deref option */
268 if ( strcasecmp( optarg, "never" ) == 0 ) {
269 deref = LDAP_DEREF_NEVER;
270 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
271 deref = LDAP_DEREF_SEARCHING;
272 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
273 deref = LDAP_DEREF_FINDING;
274 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
275 deref = LDAP_DEREF_ALWAYS;
278 _("alias deref should be never, search, find, or always\n") );
282 case 'A': /* retrieve attribute names only -- no values */
285 case 'b': /* search base */
286 base = ber_strdup( optarg );
288 case 'E': /* search extensions */
289 if( protocol == LDAP_VERSION2 ) {
290 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
292 exit( EXIT_FAILURE );
295 /* should be extended to support comma separated list of
296 * [!]key[=value] parameters, e.g. -E !foo,bar=567
301 if( optarg[0] == '!' ) {
306 control = ber_strdup( optarg );
307 if ( (cvalue = strchr( control, '=' )) != NULL ) {
311 if ( strcasecmp( control, "mv" ) == 0 ) {
312 /* ValuesReturnFilter control */
313 if( valuesReturnFilter ) {
315 _("ValuesReturnFilter previously specified\n"));
316 exit( EXIT_FAILURE );
318 valuesReturnFilter= 1 + crit;
320 if ( cvalue == NULL ) {
322 _("missing filter in ValuesReturnFilter control\n"));
323 exit( EXIT_FAILURE );
327 protocol = LDAP_VERSION3;
329 } else if ( strcasecmp( control, "pr" ) == 0 ) {
331 /* PagedResults control */
332 if ( pagedResults != 0 ) {
334 _("PagedResultsControl previously specified\n") );
335 exit( EXIT_FAILURE );
338 if( cvalue != NULL ) {
341 promptp = strchr( cvalue, '/' );
342 if ( promptp != NULL ) {
344 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
346 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
350 _("Invalid value for PagedResultsControl,"
351 " %s/%s.\n"), cvalue, promptp );
352 exit( EXIT_FAILURE );
355 num = sscanf( cvalue, "%d", &tmp );
358 _("Invalid value for PagedResultsControl, %s.\n"),
360 exit( EXIT_FAILURE );
363 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
364 exit( EXIT_FAILURE );
366 pageSize = (ber_int_t) tmp;
367 pagedResults = 1 + crit;
369 #ifdef LDAP_CONTROL_DONTUSECOPY
370 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
373 _("dontUseCopy control previously specified\n"));
374 exit( EXIT_FAILURE );
376 if( cvalue != NULL ) {
378 _("dontUseCopy: no control value expected\n") );
383 _("dontUseCopy: critical flag required\n") );
387 dontUseCopy = 1 + crit;
389 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
392 _("domainScope control previously specified\n"));
393 exit( EXIT_FAILURE );
395 if( cvalue != NULL ) {
397 _("domainScope: no control value expected\n") );
401 domainScope = 1 + crit;
403 } else if ( strcasecmp( control, "sss" ) == 0 ) {
407 _("server side sorting control previously specified\n"));
408 exit( EXIT_FAILURE );
410 if( cvalue == NULL ) {
412 _("missing specification of sss control\n") );
413 exit( EXIT_FAILURE );
416 while ( ( keyp = strchr(keyp, '/') ) != NULL ) {
419 if ( ldap_create_sort_keylist( &sss_keys, cvalue )) {
421 _("server side sorting control value \"%s\" invalid\n"),
423 exit( EXIT_FAILURE );
428 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
431 _("subentries control previously specified\n"));
432 exit( EXIT_FAILURE );
434 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
436 } else if ( strcasecmp( cvalue, "false") == 0 ) {
440 _("subentries control value \"%s\" invalid\n"),
442 exit( EXIT_FAILURE );
444 if( crit ) subentries *= -1;
446 } else if ( strcasecmp( control, "sync" ) == 0 ) {
450 fprintf( stderr, _("sync control previously specified\n") );
451 exit( EXIT_FAILURE );
453 if ( cvalue == NULL ) {
454 fprintf( stderr, _("missing specification of sync control\n"));
455 exit( EXIT_FAILURE );
457 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
458 ldapsync = LDAP_SYNC_REFRESH_ONLY;
459 cookiep = strchr( cvalue, '/' );
460 if ( cookiep != NULL ) {
462 if ( *cookiep != '\0' ) {
463 ber_str2bv( cookiep, 0, 0, &sync_cookie );
466 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
467 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
468 cookiep = strchr( cvalue, '/' );
469 if ( cookiep != NULL ) {
473 slimitp = strchr( cvalue, '/' );
474 if ( slimitp != NULL ) {
477 if ( cookiep != NULL && *cookiep != '\0' )
478 ber_str2bv( cookiep, 0, 0, &sync_cookie );
479 if ( slimitp != NULL && *slimitp != '\0' ) {
480 ival = strtol( slimitp, &next, 10 );
481 if ( next == NULL || next[0] != '\0' ) {
482 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
483 exit( EXIT_FAILURE );
488 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
490 exit( EXIT_FAILURE );
492 if ( crit ) ldapsync *= -1;
494 } else if ( tool_is_oid( control ) ) {
496 exit( EXIT_FAILURE );
500 c[ nctrls - 1 ].ldctl_oid = control;
503 if ( cvalue == NULL ) {
504 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
505 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
507 } else if ( cvalue[ 0 ] == ':' ) {
515 * to use ldif_parse_line2() */
517 ldif_parse_line2( &cvalue[ -2 ], &type,
522 c[ nctrls - 1 ].ldctl_value = value;
525 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
530 c[ nctrls - 1 ].ldctl_iscritical = crit;
533 fprintf( stderr, _("Invalid search extension name: %s\n"),
538 case 'F': /* uri prefix */
539 if( urlpre ) free( urlpre );
540 urlpre = strdup( optarg );
542 case 'l': /* time limit */
543 if ( strcasecmp( optarg, "none" ) == 0 ) {
546 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
547 timelimit = LDAP_MAXINT;
550 ival = strtol( optarg, &next, 10 );
551 if ( next == NULL || next[0] != '\0' ) {
553 _("Unable to parse time limit \"%s\"\n"), optarg );
554 exit( EXIT_FAILURE );
558 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
559 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
561 exit( EXIT_FAILURE );
564 case 'L': /* print entries in LDIF format */
567 case 's': /* search scope */
568 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
569 scope = LDAP_SCOPE_BASE;
570 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
571 scope = LDAP_SCOPE_ONELEVEL;
572 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
573 || ( strcasecmp( optarg, "children" ) == 0 ))
575 scope = LDAP_SCOPE_SUBORDINATE;
576 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
577 scope = LDAP_SCOPE_SUBTREE;
579 fprintf( stderr, _("scope should be base, one, or sub\n") );
583 case 'S': /* sort attribute */
584 sortattr = strdup( optarg );
586 case 't': /* write attribute values to TMPDIR files */
589 case 'T': /* tmpdir */
590 if( tmpdir ) free( tmpdir );
591 tmpdir = strdup( optarg );
593 case 'u': /* include UFN */
596 case 'z': /* size limit */
597 if ( strcasecmp( optarg, "none" ) == 0 ) {
600 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
601 sizelimit = LDAP_MAXINT;
604 ival = strtol( optarg, &next, 10 );
605 if ( next == NULL || next[0] != '\0' ) {
607 _("Unable to parse size limit \"%s\"\n"), optarg );
608 exit( EXIT_FAILURE );
612 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
613 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
615 exit( EXIT_FAILURE );
626 private_conn_setup( LDAP *ld )
629 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
630 != LDAP_OPT_SUCCESS )
632 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
633 exit( EXIT_FAILURE );
636 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
637 != LDAP_OPT_SUCCESS )
640 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
641 exit( EXIT_FAILURE );
644 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
645 != LDAP_OPT_SUCCESS )
648 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
649 exit( EXIT_FAILURE );
654 main( int argc, char **argv )
656 char *filtpattern, **attrs = NULL, line[BUFSIZ];
658 int rc, rc1, i, first;
660 BerElement *seber = NULL, *vrber = NULL;
662 BerElement *syncber = NULL;
663 struct berval *syncbvalp = NULL;
666 tool_init( TOOL_SEARCH );
668 npagedresponses = npagedentries = npagedreferences =
669 npagedextended = npagedpartial = 0;
671 prog = lutil_progname( "ldapsearch", argc, argv );
673 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
674 (def_tmpdir = getenv("TMP")) == NULL &&
675 (def_tmpdir = getenv("TEMP")) == NULL )
677 def_tmpdir = LDAP_TMPDIR;
681 def_tmpdir = LDAP_TMPDIR;
683 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
685 if( def_urlpre == NULL ) {
690 sprintf( def_urlpre, "file:///%s/",
691 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
693 urlize( def_urlpre );
695 tool_args( argc, argv );
697 if (( argc - optind < 1 ) ||
698 ( *argv[optind] != '(' /*')'*/ &&
699 ( strchr( argv[optind], '=' ) == NULL ) ) )
701 filtpattern = "(objectclass=*)";
703 filtpattern = argv[optind++];
706 if ( argv[optind] != NULL ) {
707 attrs = &argv[optind];
710 if ( infile != NULL ) {
713 if ( infile[0] == '-' && infile[1] == '\0' ) {
715 } else if (( fp = fopen( infile, "r" )) == NULL ) {
720 for( i=0 ; filtpattern[i] ; i++ ) {
721 if( filtpattern[i] == '%' ) {
723 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
730 if( filtpattern[i+1] != 's' ) {
731 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
739 if ( tmpdir == NULL ) {
742 if ( urlpre == NULL )
746 if( urlpre == NULL ) {
747 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
749 if( urlpre == NULL ) {
754 sprintf( urlpre, "file:///%s/",
755 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
763 ld = tool_conn_setup( 0, &private_conn_setup );
765 if ( pw_file || want_bindpw ) {
767 rc = lutil_get_filed_password( pw_file, &passwd );
768 if( rc ) return EXIT_FAILURE;
770 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
771 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
778 save_nctrls = nctrls;
781 #ifdef LDAP_CONTROL_DONTUSECOPY
789 || valuesReturnFilter )
792 #ifdef LDAP_CONTROL_DONTUSECOPY
798 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
799 c[i].ldctl_value.bv_val = NULL;
800 c[i].ldctl_value.bv_len = 0;
801 c[i].ldctl_iscritical = dontUseCopy > 1;
811 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
812 c[i].ldctl_value.bv_val = NULL;
813 c[i].ldctl_value.bv_len = 0;
814 c[i].ldctl_iscritical = domainScope > 1;
823 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
827 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
829 ber_free( seber, 1 );
830 fprintf( stderr, _("Subentries control encoding error!\n") );
834 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
838 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
839 c[i].ldctl_iscritical = subentries < 1;
848 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
852 if ( sync_cookie.bv_len == 0 ) {
853 err = ber_printf( syncber, "{e}", abs(ldapsync) );
855 err = ber_printf( syncber, "{eO}", abs(ldapsync),
859 if ( err == LBER_ERROR ) {
860 ber_free( syncber, 1 );
861 fprintf( stderr, _("ldap sync control encoding error!\n") );
865 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
869 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
870 c[i].ldctl_value = (*syncbvalp);
871 c[i].ldctl_iscritical = ldapsync < 0;
875 if ( valuesReturnFilter ) {
880 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
884 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
885 ber_free( vrber, 1 );
886 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
890 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
894 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
895 c[i].ldctl_iscritical = valuesReturnFilter > 1;
899 if ( pagedResults ) {
904 if ( ldap_create_page_control_value( ld,
905 pageSize, &pr_cookie, &c[i].ldctl_value ) )
910 if ( pr_cookie.bv_val != NULL ) {
911 ber_memfree( pr_cookie.bv_val );
912 pr_cookie.bv_val = NULL;
913 pr_cookie.bv_len = 0;
916 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
917 c[i].ldctl_iscritical = pagedResults > 1;
926 if ( ldap_create_sort_control_value( ld,
927 sss_keys, &c[i].ldctl_value ) )
932 c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
933 c[i].ldctl_iscritical = sss > 1;
938 tool_server_controls( ld, c, i );
940 ber_free( seber, 1 );
941 ber_free( vrber, 1 );
943 /* step back to the original number of controls, so that
944 * those set while parsing args are preserved */
945 nctrls = save_nctrls;
948 fprintf( stderr, _("filter%s: %s\nrequesting: "),
949 infile != NULL ? _(" pattern") : "",
952 if ( attrs == NULL ) {
953 fprintf( stderr, _("All userApplication attributes") );
955 for ( i = 0; attrs[ i ] != NULL; ++i ) {
956 fprintf( stderr, "%s ", attrs[ i ] );
959 fprintf( stderr, "\n" );
963 printf( _("# extended LDIF\n") );
964 } else if ( ldif < 3 ) {
965 printf( _("version: %d\n\n"), 1 );
969 char *realbase = base;
971 if ( realbase == NULL ) {
972 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
976 printf(_("# LDAPv%d\n"), protocol);
977 printf(_("# base <%s>%s with scope %s\n"),
978 realbase ? realbase : "",
979 ( realbase == NULL || realbase != base ) ? " (default)" : "",
980 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
981 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
982 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
984 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
986 printf(_("# requesting: "));
988 if ( attrs == NULL ) {
991 for ( i = 0; attrs[ i ] != NULL; ++i ) {
992 printf( "%s ", attrs[ i ] );
997 printf(_("\n# with manageDSAit %scontrol"),
998 manageDSAit > 1 ? _("critical ") : "" );
1001 printf(_("\n# with noop %scontrol"),
1002 noop > 1 ? _("critical ") : "" );
1005 printf(_("\n# with subentries %scontrol: %s"),
1006 subentries < 0 ? _("critical ") : "",
1007 abs(subentries) == 1 ? "false" : "true" );
1009 if ( valuesReturnFilter ) {
1010 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1011 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1013 if ( pagedResults ) {
1014 printf(_("\n# with pagedResults %scontrol: size=%d"),
1015 (pagedResults > 1) ? _("critical ") : "",
1019 printf(_("\n# with server side sorting %scontrol"),
1020 sss > 1 ? _("critical ") : "" );
1023 printf( _("\n#\n\n") );
1025 if ( realbase && realbase != base ) {
1026 ldap_memfree( realbase );
1030 if ( infile == NULL ) {
1031 rc = dosearch( ld, base, scope, NULL, filtpattern,
1032 attrs, attrsonly, NULL, NULL, NULL, -1 );
1037 while ( fgets( line, sizeof( line ), fp ) != NULL ) {
1038 line[ strlen( line ) - 1 ] = '\0';
1044 rc1 = dosearch( ld, base, scope, filtpattern, line,
1045 attrs, attrsonly, NULL, NULL, NULL, -1 );
1053 if ( fp != stdin ) {
1058 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1060 int i, moreEntries, tmpSize;
1062 /* Loop to get the next pages when
1063 * enter is pressed on the terminal.
1065 if ( pagePrompt != 0 ) {
1066 if ( entriesLeft > 0 ) {
1067 printf( _("Estimate entries: %d\n"), entriesLeft );
1069 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1072 moreEntries = getchar();
1073 while ( moreEntries != EOF && moreEntries != '\n' ) {
1074 if ( i < (int)sizeof(buf) - 1 ) {
1075 buf[i] = moreEntries;
1078 moreEntries = getchar();
1082 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1083 int num = sscanf( buf, "%d", &tmpSize );
1086 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1087 return EXIT_FAILURE;
1090 pageSize = (ber_int_t)tmpSize;
1099 if ( base != NULL ) {
1100 ber_memfree( base );
1102 if ( control != NULL ) {
1103 ber_memfree( control );
1105 if ( sss_keys != NULL ) {
1106 ldap_free_sort_keylist( sss_keys );
1110 for ( ; save_nctrls-- > 0; ) {
1111 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1121 static int dosearch(
1129 LDAPControl **sctrls,
1130 LDAPControl **cctrls,
1131 struct timeval *timeout,
1141 LDAPMessage *res, *msg;
1143 char *retoid = NULL;
1144 struct berval *retdata = NULL;
1145 int nresponses_psearch = -1;
1146 int cancel_msgid = -1;
1148 if( filtpatt != NULL ) {
1149 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1;
1150 filter = malloc( max_fsize );
1151 if( filter == NULL ) {
1153 return EXIT_FAILURE;
1156 if( snprintf( filter, max_fsize, filtpatt, value ) >= max_fsize ) {
1157 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1159 return EXIT_FAILURE;
1163 fprintf( stderr, _("filter: %s\n"), filter );
1167 printf( _("#\n# filter: %s\n#\n"), filter );
1175 if ( filtpatt != NULL ) {
1178 return LDAP_SUCCESS;
1181 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1182 sctrls, cctrls, timeout, sizelimit, &msgid );
1184 if ( filtpatt != NULL ) {
1188 if( rc != LDAP_SUCCESS ) {
1189 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1190 prog, ldap_err2string( rc ), rc );
1194 nresponses = nentries = nreferences = nextended = npartial = 0;
1198 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1199 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1202 rc = tool_check_abandon( ld, msgid );
1208 (void) ldap_sort_entries( ld, &res,
1209 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1212 for ( msg = ldap_first_message( ld, res );
1214 msg = ldap_next_message( ld, msg ) )
1216 if ( nresponses++ ) putchar('\n');
1217 if ( nresponses_psearch >= 0 )
1218 nresponses_psearch++;
1220 switch( ldap_msgtype( msg ) ) {
1221 case LDAP_RES_SEARCH_ENTRY:
1223 print_entry( ld, msg, attrsonly );
1226 case LDAP_RES_SEARCH_REFERENCE:
1228 print_reference( ld, msg );
1231 case LDAP_RES_EXTENDED:
1233 print_extended( ld, msg );
1235 if ( ldap_msgid( msg ) == 0 ) {
1236 /* unsolicited extended operation */
1240 if ( cancel_msgid != -1 &&
1241 cancel_msgid == ldap_msgid( msg ) ) {
1242 printf(_("Cancelled \n"));
1243 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1248 case LDAP_RES_SEARCH_RESULT:
1249 /* pagedResults stuff is dealt with
1250 * in tool_print_ctrls(), called by
1251 * print_results(). */
1252 rc = print_result( ld, msg, 1 );
1253 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1259 case LDAP_RES_INTERMEDIATE:
1261 ldap_parse_intermediate( ld, msg,
1262 &retoid, &retdata, NULL, 0 );
1264 nresponses_psearch = 0;
1266 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1267 printf(_("SyncInfo Received\n"));
1268 ldap_memfree( retoid );
1269 ber_bvfree( retdata );
1273 print_partial( ld, msg );
1274 ldap_memfree( retoid );
1275 ber_bvfree( retdata );
1279 if ( ldapsync && sync_slimit != -1 &&
1280 nresponses_psearch >= sync_slimit ) {
1281 BerElement *msgidber = NULL;
1282 struct berval *msgidvalp = NULL;
1283 msgidber = ber_alloc_t(LBER_USE_DER);
1284 ber_printf(msgidber, "{i}", msgid);
1285 ber_flatten(msgidber, &msgidvalp);
1286 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1287 msgidvalp, NULL, NULL, &cancel_msgid);
1288 nresponses_psearch = -1;
1292 ldap_msgfree( res );
1297 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1301 ldap_msgfree( res );
1303 if ( pagedResults ) {
1304 npagedresponses += nresponses;
1305 npagedentries += nentries;
1306 npagedextended += nextended;
1307 npagedpartial += npartial;
1308 npagedreferences += nreferences;
1309 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1310 printf( _("\n# numResponses: %d\n"), npagedresponses );
1311 if( npagedentries ) {
1312 printf( _("# numEntries: %d\n"), npagedentries );
1314 if( npagedextended ) {
1315 printf( _("# numExtended: %d\n"), npagedextended );
1317 if( npagedpartial ) {
1318 printf( _("# numPartial: %d\n"), npagedpartial );
1320 if( npagedreferences ) {
1321 printf( _("# numReferences: %d\n"), npagedreferences );
1324 } else if ( ldif < 2 ) {
1325 printf( _("\n# numResponses: %d\n"), nresponses );
1326 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1327 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1328 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1329 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1335 /* This is the proposed new way of doing things.
1336 * It is more efficient, but the API is non-standard.
1345 char tmpfname[ 256 ];
1348 BerElement *ber = NULL;
1349 struct berval bv, *bvals, **bvp = &bvals;
1350 LDAPControl **ctrls = NULL;
1353 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1356 ufn = ldap_dn2ufn( bv.bv_val );
1357 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1359 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1361 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1362 if( rc != LDAP_SUCCESS ) {
1363 fprintf(stderr, _("print_entry: %d\n"), rc );
1364 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1365 exit( EXIT_FAILURE );
1369 tool_print_ctrls( ld, ctrls );
1370 ldap_controls_free( ctrls );
1375 ufn = ldap_dn2ufn( bv.bv_val );
1377 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1380 if( ufn != NULL ) ldap_memfree( ufn );
1382 if ( attrsonly ) bvp = NULL;
1384 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1386 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1388 if (bv.bv_val == NULL) break;
1391 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1393 } else if ( bvals ) {
1394 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1395 if ( vals2tmp > 1 || ( vals2tmp &&
1396 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1399 /* write value to file */
1400 snprintf( tmpfname, sizeof tmpfname,
1401 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1402 tmpdir, bv.bv_val );
1405 tmpfd = mkstemp( tmpfname );
1412 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1417 if ( fwrite( bvals[ i ].bv_val,
1418 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1427 snprintf( url, sizeof url, "%s%s", urlpre,
1428 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1431 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1434 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1435 bvals[ i ].bv_val, bvals[ i ].bv_len );
1438 ber_memfree( bvals );
1447 static void print_reference(
1449 LDAPMessage *reference )
1453 LDAPControl **ctrls;
1456 printf(_("# search reference\n"));
1459 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1461 if( rc != LDAP_SUCCESS ) {
1462 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1463 exit( EXIT_FAILURE );
1468 for( i=0; refs[i] != NULL; i++ ) {
1469 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1470 "ref", refs[i], strlen(refs[i]) );
1472 ber_memvfree( (void **) refs );
1476 tool_print_ctrls( ld, ctrls );
1477 ldap_controls_free( ctrls );
1481 static void print_extended(
1483 LDAPMessage *extended )
1486 char *retoid = NULL;
1487 struct berval *retdata = NULL;
1490 printf(_("# extended result response\n"));
1493 rc = ldap_parse_extended_result( ld, extended,
1494 &retoid, &retdata, 0 );
1496 if( rc != LDAP_SUCCESS ) {
1497 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1498 exit( EXIT_FAILURE );
1502 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1503 "extended", retoid, retoid ? strlen(retoid) : 0 );
1505 ber_memfree( retoid );
1509 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1510 "data", retdata->bv_val, retdata->bv_len );
1512 ber_bvfree( retdata );
1515 print_result( ld, extended, 0 );
1518 static void print_partial(
1520 LDAPMessage *partial )
1523 char *retoid = NULL;
1524 struct berval *retdata = NULL;
1525 LDAPControl **ctrls = NULL;
1528 printf(_("# extended partial response\n"));
1531 rc = ldap_parse_intermediate( ld, partial,
1532 &retoid, &retdata, &ctrls, 0 );
1534 if( rc != LDAP_SUCCESS ) {
1535 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1536 exit( EXIT_FAILURE );
1540 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1541 "partial", retoid, retoid ? strlen(retoid) : 0 );
1544 ber_memfree( retoid );
1548 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1549 "data", retdata->bv_val, retdata->bv_len );
1552 ber_bvfree( retdata );
1556 tool_print_ctrls( ld, ctrls );
1557 ldap_controls_free( ctrls );
1561 static int print_result(
1563 LDAPMessage *result, int search )
1567 char *matcheddn = NULL;
1570 LDAPControl **ctrls = NULL;
1574 printf(_("# search result\n"));
1577 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1581 rc = ldap_parse_result( ld, result,
1582 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1584 if( rc != LDAP_SUCCESS ) {
1585 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1586 exit( EXIT_FAILURE );
1591 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1593 } else if ( err != LDAP_SUCCESS ) {
1594 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1600 tool_write_ldif( LDIF_PUT_VALUE,
1601 "matchedDN", matcheddn, strlen(matcheddn) );
1603 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1607 ber_memfree( matcheddn );
1613 if ( err == LDAP_PARTIAL_RESULTS ) {
1616 for ( line = text; line != NULL; ) {
1617 char *next = strchr( line, '\n' );
1619 tool_write_ldif( LDIF_PUT_TEXT,
1621 next ? next - line : strlen( line ) );
1623 line = next ? next + 1 : NULL;
1627 tool_write_ldif( LDIF_PUT_TEXT, "text",
1628 text, strlen(text) );
1631 fprintf( stderr, _("Additional information: %s\n"), text );
1635 ber_memfree( text );
1640 for( i=0; refs[i] != NULL; i++ ) {
1642 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1644 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1648 ber_memvfree( (void **) refs );
1651 pr_morePagedResults = 0;
1654 tool_print_ctrls( ld, ctrls );
1655 ldap_controls_free( ctrls );