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),
860 ber_free( syncber, 1 );
861 fprintf( stderr, _("ldap sync control encoding error!\n") );
865 if ( ber_flatten( syncber, &syncbvalp ) == -1 ) {
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, outlen;
1150 filter = malloc( max_fsize );
1151 if( filter == NULL ) {
1153 return EXIT_FAILURE;
1156 outlen = snprintf( filter, max_fsize, filtpatt, value );
1157 if( outlen >= max_fsize ) {
1158 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1160 return EXIT_FAILURE;
1164 fprintf( stderr, _("filter: %s\n"), filter );
1168 printf( _("#\n# filter: %s\n#\n"), filter );
1176 if ( filtpatt != NULL ) {
1179 return LDAP_SUCCESS;
1182 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1183 sctrls, cctrls, timeout, sizelimit, &msgid );
1185 if ( filtpatt != NULL ) {
1189 if( rc != LDAP_SUCCESS ) {
1190 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1191 prog, ldap_err2string( rc ), rc );
1195 nresponses = nentries = nreferences = nextended = npartial = 0;
1199 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1200 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1203 rc = tool_check_abandon( ld, msgid );
1209 (void) ldap_sort_entries( ld, &res,
1210 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1213 for ( msg = ldap_first_message( ld, res );
1215 msg = ldap_next_message( ld, msg ) )
1217 if ( nresponses++ ) putchar('\n');
1218 if ( nresponses_psearch >= 0 )
1219 nresponses_psearch++;
1221 switch( ldap_msgtype( msg ) ) {
1222 case LDAP_RES_SEARCH_ENTRY:
1224 print_entry( ld, msg, attrsonly );
1227 case LDAP_RES_SEARCH_REFERENCE:
1229 print_reference( ld, msg );
1232 case LDAP_RES_EXTENDED:
1234 print_extended( ld, msg );
1236 if ( ldap_msgid( msg ) == 0 ) {
1237 /* unsolicited extended operation */
1241 if ( cancel_msgid != -1 &&
1242 cancel_msgid == ldap_msgid( msg ) ) {
1243 printf(_("Cancelled \n"));
1244 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1249 case LDAP_RES_SEARCH_RESULT:
1250 /* pagedResults stuff is dealt with
1251 * in tool_print_ctrls(), called by
1252 * print_results(). */
1253 rc = print_result( ld, msg, 1 );
1254 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1260 case LDAP_RES_INTERMEDIATE:
1262 ldap_parse_intermediate( ld, msg,
1263 &retoid, &retdata, NULL, 0 );
1265 nresponses_psearch = 0;
1267 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1268 printf(_("SyncInfo Received\n"));
1269 ldap_memfree( retoid );
1270 ber_bvfree( retdata );
1274 print_partial( ld, msg );
1275 ldap_memfree( retoid );
1276 ber_bvfree( retdata );
1280 if ( ldapsync && sync_slimit != -1 &&
1281 nresponses_psearch >= sync_slimit ) {
1282 BerElement *msgidber = NULL;
1283 struct berval *msgidvalp = NULL;
1284 msgidber = ber_alloc_t(LBER_USE_DER);
1285 ber_printf(msgidber, "{i}", msgid);
1286 ber_flatten(msgidber, &msgidvalp);
1287 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1288 msgidvalp, NULL, NULL, &cancel_msgid);
1289 nresponses_psearch = -1;
1293 ldap_msgfree( res );
1298 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1302 ldap_msgfree( res );
1304 if ( pagedResults ) {
1305 npagedresponses += nresponses;
1306 npagedentries += nentries;
1307 npagedextended += nextended;
1308 npagedpartial += npartial;
1309 npagedreferences += nreferences;
1310 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1311 printf( _("\n# numResponses: %d\n"), npagedresponses );
1312 if( npagedentries ) {
1313 printf( _("# numEntries: %d\n"), npagedentries );
1315 if( npagedextended ) {
1316 printf( _("# numExtended: %d\n"), npagedextended );
1318 if( npagedpartial ) {
1319 printf( _("# numPartial: %d\n"), npagedpartial );
1321 if( npagedreferences ) {
1322 printf( _("# numReferences: %d\n"), npagedreferences );
1325 } else if ( ldif < 2 ) {
1326 printf( _("\n# numResponses: %d\n"), nresponses );
1327 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1328 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1329 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1330 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1336 /* This is the proposed new way of doing things.
1337 * It is more efficient, but the API is non-standard.
1346 char tmpfname[ 256 ];
1349 BerElement *ber = NULL;
1350 struct berval bv, *bvals, **bvp = &bvals;
1351 LDAPControl **ctrls = NULL;
1354 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1357 ufn = ldap_dn2ufn( bv.bv_val );
1358 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1360 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1362 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1363 if( rc != LDAP_SUCCESS ) {
1364 fprintf(stderr, _("print_entry: %d\n"), rc );
1365 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1366 exit( EXIT_FAILURE );
1370 tool_print_ctrls( ld, ctrls );
1371 ldap_controls_free( ctrls );
1376 ufn = ldap_dn2ufn( bv.bv_val );
1378 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1381 if( ufn != NULL ) ldap_memfree( ufn );
1383 if ( attrsonly ) bvp = NULL;
1385 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1387 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1389 if (bv.bv_val == NULL) break;
1392 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1394 } else if ( bvals ) {
1395 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1396 if ( vals2tmp > 1 || ( vals2tmp &&
1397 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1400 /* write value to file */
1401 snprintf( tmpfname, sizeof tmpfname,
1402 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1403 tmpdir, bv.bv_val );
1406 tmpfd = mkstemp( tmpfname );
1413 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1418 if ( fwrite( bvals[ i ].bv_val,
1419 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1428 snprintf( url, sizeof url, "%s%s", urlpre,
1429 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1432 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1435 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1436 bvals[ i ].bv_val, bvals[ i ].bv_len );
1439 ber_memfree( bvals );
1448 static void print_reference(
1450 LDAPMessage *reference )
1454 LDAPControl **ctrls;
1457 printf(_("# search reference\n"));
1460 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1462 if( rc != LDAP_SUCCESS ) {
1463 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1464 exit( EXIT_FAILURE );
1469 for( i=0; refs[i] != NULL; i++ ) {
1470 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1471 "ref", refs[i], strlen(refs[i]) );
1473 ber_memvfree( (void **) refs );
1477 tool_print_ctrls( ld, ctrls );
1478 ldap_controls_free( ctrls );
1482 static void print_extended(
1484 LDAPMessage *extended )
1487 char *retoid = NULL;
1488 struct berval *retdata = NULL;
1491 printf(_("# extended result response\n"));
1494 rc = ldap_parse_extended_result( ld, extended,
1495 &retoid, &retdata, 0 );
1497 if( rc != LDAP_SUCCESS ) {
1498 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1499 exit( EXIT_FAILURE );
1503 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1504 "extended", retoid, retoid ? strlen(retoid) : 0 );
1506 ber_memfree( retoid );
1510 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1511 "data", retdata->bv_val, retdata->bv_len );
1513 ber_bvfree( retdata );
1516 print_result( ld, extended, 0 );
1519 static void print_partial(
1521 LDAPMessage *partial )
1524 char *retoid = NULL;
1525 struct berval *retdata = NULL;
1526 LDAPControl **ctrls = NULL;
1529 printf(_("# extended partial response\n"));
1532 rc = ldap_parse_intermediate( ld, partial,
1533 &retoid, &retdata, &ctrls, 0 );
1535 if( rc != LDAP_SUCCESS ) {
1536 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1537 exit( EXIT_FAILURE );
1541 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1542 "partial", retoid, retoid ? strlen(retoid) : 0 );
1545 ber_memfree( retoid );
1549 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1550 "data", retdata->bv_val, retdata->bv_len );
1553 ber_bvfree( retdata );
1557 tool_print_ctrls( ld, ctrls );
1558 ldap_controls_free( ctrls );
1562 static int print_result(
1564 LDAPMessage *result, int search )
1568 char *matcheddn = NULL;
1571 LDAPControl **ctrls = NULL;
1575 printf(_("# search result\n"));
1578 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1582 rc = ldap_parse_result( ld, result,
1583 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1585 if( rc != LDAP_SUCCESS ) {
1586 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1587 exit( EXIT_FAILURE );
1592 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1594 } else if ( err != LDAP_SUCCESS ) {
1595 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1601 tool_write_ldif( LDIF_PUT_VALUE,
1602 "matchedDN", matcheddn, strlen(matcheddn) );
1604 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1608 ber_memfree( matcheddn );
1614 if ( err == LDAP_PARTIAL_RESULTS ) {
1617 for ( line = text; line != NULL; ) {
1618 char *next = strchr( line, '\n' );
1620 tool_write_ldif( LDIF_PUT_TEXT,
1622 next ? (size_t) (next - line) : strlen( line ));
1624 line = next ? next + 1 : NULL;
1628 tool_write_ldif( LDIF_PUT_TEXT, "text",
1629 text, strlen(text) );
1632 fprintf( stderr, _("Additional information: %s\n"), text );
1636 ber_memfree( text );
1641 for( i=0; refs[i] != NULL; i++ ) {
1643 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1645 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1649 ber_memvfree( (void **) refs );
1652 pr_morePagedResults = 0;
1655 tool_print_ctrls( ld, ctrls );
1656 ldap_controls_free( ctrls );