1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2004 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>
54 #ifdef HAVE_SYS_TYPES_H
55 #include <sys/types.h>
65 #include "lutil_ldap.h"
66 #include "ldap_defaults.h"
73 static int scope = LDAP_SCOPE_SUBTREE;
74 static int deref = -1;
76 static int timelimit = -1;
77 static int sizelimit = -1;
79 static char *def_tmpdir;
80 static char *def_urlpre;
82 #if defined(__CYGWIN__) || defined(__MINGW32__)
83 /* Turn off commandline globbing, otherwise you cannot search for
92 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
93 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
94 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
95 fprintf( stderr, _(" which may include:\n"));
96 fprintf( stderr, _(" 1.1 no attributes\n"));
97 fprintf( stderr, _(" * all user attributes\n"));
98 fprintf( stderr, _(" + all operational attributes\n"));
101 fprintf( stderr, _("Search options:\n"));
102 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
103 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
104 fprintf( stderr, _(" -b basedn base dn for search\n"));
105 fprintf( stderr, _(" -E [!]<ctrl>[=<ctrlparam>] search controls (! indicates criticality)\n"));
106 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
107 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
109 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
110 #ifdef LDAP_CONTROL_PAGEDRESULTS
111 fprintf( stderr, _(" [!]pr=<size> (paged results)\n"));
113 #ifdef LDAP_CONTROL_SUBENTRIES
114 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
116 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
117 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
118 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
119 fprintf( stderr, _(" -l limit time limit (in seconds) for search\n"));
120 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
121 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
122 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
123 fprintf( stderr, _(" and version\n"));
124 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
125 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
126 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
127 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
128 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
129 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
130 fprintf( stderr, _(" -z limit size limit (in entries) for search\n"));
132 exit( EXIT_FAILURE );
135 static void print_entry LDAP_P((
140 static void print_reference(
142 LDAPMessage *reference );
144 static void print_extended(
146 LDAPMessage *extended );
148 static void print_partial(
150 LDAPMessage *partial );
152 static int print_result(
157 static void print_ctrls(
158 LDAPControl **ctrls );
160 static int write_ldif LDAP_P((
166 static int dosearch LDAP_P((
174 LDAPControl **sctrls,
175 LDAPControl **cctrls,
176 struct timeval *timeout,
179 static char *tmpdir = NULL;
180 static char *urlpre = NULL;
181 static char *base = NULL;
182 static char *sortattr = NULL;
183 static int includeufn, vals2tmp = 0, ldif = 0;
185 static int subentries = 0, valuesReturnFilter = 0;
186 static char *vrFilter = NULL;
188 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
189 static int domainScope = 0;
192 static int ldapsync = 0;
193 static struct berval sync_cookie = { 0, NULL };
194 static int sync_slimit = -1;
196 #ifdef LDAP_CONTROL_PAGEDRESULTS
197 static int pagedResults = 0;
198 static ber_int_t pageSize = 0;
199 static ber_int_t entriesLeft = 0;
200 static ber_int_t morePagedResults = 1;
201 static struct berval cookie = { 0, NULL };
202 static int npagedresponses;
203 static int npagedentries;
204 static int npagedreferences;
205 static int npagedextended;
206 static int npagedpartial;
208 static int parse_page_control(
211 struct berval *cookie );
219 if (*LDAP_DIRSEP != '/') {
220 for (p = url; *p; p++) {
221 if (*p == *LDAP_DIRSEP)
228 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
229 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
232 handle_private_option( int i )
235 char *control, *cvalue;
237 case 'a': /* set alias deref option */
238 if ( strcasecmp( optarg, "never" ) == 0 ) {
239 deref = LDAP_DEREF_NEVER;
240 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
241 deref = LDAP_DEREF_SEARCHING;
242 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
243 deref = LDAP_DEREF_FINDING;
244 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
245 deref = LDAP_DEREF_ALWAYS;
247 fprintf( stderr, _("alias deref should be never, search, find, or always\n") );
251 case 'A': /* retrieve attribute names only -- no values */
254 case 'b': /* search base */
255 base = strdup( optarg );
257 case 'E': /* search controls */
258 if( protocol == LDAP_VERSION2 ) {
259 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
261 exit( EXIT_FAILURE );
264 /* should be extended to support comma separated list of
265 * [!]key[=value] parameters, e.g. -E !foo,bar=567
270 if( optarg[0] == '!' ) {
275 control = strdup( optarg );
276 if ( (cvalue = strchr( control, '=' )) != NULL ) {
280 if ( strcasecmp( control, "mv" ) == 0 ) {
281 /* ValuesReturnFilter control */
282 if( valuesReturnFilter ) {
283 fprintf( stderr, _("ValuesReturnFilter previously specified\n"));
284 exit( EXIT_FAILURE );
286 valuesReturnFilter= 1 + crit;
288 if ( cvalue == NULL ) {
290 _("missing filter in ValuesReturnFilter control\n"));
291 exit( EXIT_FAILURE );
295 protocol = LDAP_VERSION3;
297 #ifdef LDAP_CONTROL_PAGEDRESULTS
298 } else if ( strcasecmp( control, "pr" ) == 0 ) {
300 /* PagedResults control */
301 if ( pagedResults != 0 ) {
302 fprintf( stderr, _("PagedResultsControl previously specified\n") );
303 exit( EXIT_FAILURE );
306 num = sscanf( cvalue, "%d", &tmp );
308 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), cvalue);
309 exit( EXIT_FAILURE );
312 pageSize = (ber_int_t) tmp;
313 pagedResults = 1 + crit;
316 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
317 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
320 _("domainScope control previously specified\n"));
321 exit( EXIT_FAILURE );
323 if( cvalue != NULL ) {
325 _("domainScope: no control value expected\n") );
329 domainScope = 1 + crit;
331 #ifdef LDAP_CONTROL_SUBENTRIES
332 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
334 fprintf( stderr, _("subentries control previously specified\n"));
335 exit( EXIT_FAILURE );
337 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
339 } else if ( strcasecmp( cvalue, "false") == 0 ) {
343 _("subentries control value \"%s\" invalid\n"),
345 exit( EXIT_FAILURE );
347 if( crit ) subentries *= -1;
350 } else if ( strcasecmp( control, "sync" ) == 0 ) {
354 fprintf( stderr, _("ldap sync control previously specified\n") );
355 exit( EXIT_FAILURE );
357 if ( cvalue == NULL ) {
359 _("missing specification of ldap sync control\n"));
360 exit( EXIT_FAILURE );
362 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
363 ldapsync = LDAP_SYNC_REFRESH_ONLY;
364 cookiep = strchr( cvalue, '/' );
365 if ( cookiep != NULL ) {
367 if ( *cookiep != '\0' ) {
368 ber_str2bv( cookiep, 0, 0, &sync_cookie );
371 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
372 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
373 cookiep = strchr( cvalue, '/' );
374 if ( cookiep != NULL ) {
378 slimitp = strchr( cvalue, '/' );
379 if ( slimitp != NULL ) {
382 if ( cookiep != NULL && *cookiep != '\0' )
383 ber_str2bv( cookiep, 0, 0, &sync_cookie );
384 if ( slimitp != NULL && *slimitp != '\0' )
385 sync_slimit = atoi( slimitp );
388 _("ldap sync control value \"%s\" invalid\n"),
390 exit( EXIT_FAILURE );
392 if ( crit ) ldapsync *= -1;
395 fprintf( stderr, _("Invalid control name: %s\n"), control );
399 case 'F': /* uri prefix */
400 if( urlpre ) free( urlpre );
401 urlpre = strdup( optarg );
403 case 'l': /* time limit */
404 timelimit = atoi( optarg );
405 if( timelimit < 0 ) {
406 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
408 exit( EXIT_FAILURE );
411 case 'L': /* print entries in LDIF format */
414 case 's': /* search scope */
415 if ( strcasecmp( optarg, "base" ) == 0 ) {
416 scope = LDAP_SCOPE_BASE;
417 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
418 scope = LDAP_SCOPE_ONELEVEL;
419 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
420 scope = LDAP_SCOPE_SUBTREE;
422 fprintf( stderr, _("scope should be base, one, or sub\n") );
426 case 'S': /* sort attribute */
427 sortattr = strdup( optarg );
429 case 't': /* write attribute values to TMPDIR files */
432 case 'T': /* tmpdir */
433 if( tmpdir ) free( tmpdir );
434 tmpdir = strdup( optarg );
436 case 'u': /* include UFN */
439 case 'z': /* size limit */
440 sizelimit = atoi( optarg );
450 private_conn_setup( LDAP *ld )
453 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
455 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
456 exit( EXIT_FAILURE );
458 if (timelimit != -1 &&
459 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
461 fprintf( stderr, _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
462 exit( EXIT_FAILURE );
464 if (sizelimit != -1 &&
465 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
467 fprintf( stderr, _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
468 exit( EXIT_FAILURE );
474 main( int argc, char **argv )
476 char *filtpattern, **attrs = NULL, line[BUFSIZ];
480 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
482 BerElement *syncber = NULL;
483 struct berval *syncbvalp = NULL;
487 #ifdef LDAP_CONTROL_PAGEDRESULTS
488 npagedresponses = npagedentries = npagedreferences =
489 npagedextended = npagedpartial = 0;
492 prog = lutil_progname( "ldapsearch", argc, argv );
494 lutil_log_initialize(argc, argv);
496 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
497 (def_tmpdir = getenv("TMP")) == NULL &&
498 (def_tmpdir = getenv("TEMP")) == NULL )
500 def_tmpdir = LDAP_TMPDIR;
504 def_tmpdir = LDAP_TMPDIR;
506 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
508 if( def_urlpre == NULL ) {
513 sprintf( def_urlpre, "file:///%s/",
514 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
516 urlize( def_urlpre );
518 tool_args( argc, argv );
520 if (( argc - optind < 1 ) ||
521 ( *argv[optind] != '(' /*')'*/ &&
522 ( strchr( argv[optind], '=' ) == NULL ) ) )
524 filtpattern = "(objectclass=*)";
526 filtpattern = strdup( argv[optind++] );
529 if ( argv[optind] != NULL ) {
530 attrs = &argv[optind];
533 if ( infile != NULL ) {
534 if ( infile[0] == '-' && infile[1] == '\0' ) {
536 } else if (( fp = fopen( infile, "r" )) == NULL ) {
542 if ( tmpdir == NULL ) {
545 if ( urlpre == NULL )
549 if( urlpre == NULL ) {
550 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
552 if( urlpre == NULL ) {
557 sprintf( urlpre, "file:///%s/",
558 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
566 ld = tool_conn_setup( 0, &private_conn_setup );
568 if ( pw_file || want_bindpw ) {
570 rc = lutil_get_filed_password( pw_file, &passwd );
571 if( rc ) return EXIT_FAILURE;
573 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
574 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
581 if ( assertion || authzid || manageDSAit || noop
582 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
585 #ifdef LDAP_CONTROL_PAGEDRESULTS
589 || subentries || valuesReturnFilter )
595 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
597 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
598 c[i].ldctl_value.bv_val = NULL;
599 c[i].ldctl_value.bv_len = 0;
600 c[i].ldctl_iscritical = domainScope > 1;
605 #ifdef LDAP_CONTROL_SUBENTRIES
607 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
611 err = ber_printf( seber, "{b}", abs(subentries) == 1 ? 0 : 1 );
613 ber_free( seber, 1 );
614 fprintf( stderr, _("Subentries control encoding error!\n") );
618 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
622 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
623 c[i].ldctl_iscritical = subentries < 1;
629 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
633 if ( sync_cookie.bv_len == 0 ) {
634 err = ber_printf( syncber, "{e}", abs(ldapsync) );
636 err = ber_printf( syncber, "{eO}", abs(ldapsync),
640 if ( err == LBER_ERROR ) {
641 ber_free( syncber, 1 );
642 fprintf( stderr, _("ldap sync control encoding error!\n") );
646 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
650 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
651 c[i].ldctl_value = (*syncbvalp);
652 c[i].ldctl_iscritical = ldapsync < 0;
656 if ( valuesReturnFilter ) {
657 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
661 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
662 ber_free( vrber, 1 );
663 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
667 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
671 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
672 c[i].ldctl_iscritical = valuesReturnFilter > 1;
676 #ifdef LDAP_CONTROL_PAGEDRESULTS
677 if ( pagedResults ) {
678 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
682 ber_printf( prber, "{iO}", pageSize, &cookie );
683 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
687 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
688 c[i].ldctl_iscritical = pagedResults > 1;
693 tool_server_controls( ld, c, i );
695 ber_free( seber, 1 );
696 ber_free( vrber, 1 );
697 ber_free( prber, 1 );
701 fprintf( stderr, _("filter%s: %s\nrequesting: "),
702 infile != NULL ? _(" pattern") : "",
705 if ( attrs == NULL ) {
706 fprintf( stderr, _("ALL") );
708 for ( i = 0; attrs[ i ] != NULL; ++i ) {
709 fprintf( stderr, "%s ", attrs[ i ] );
712 fprintf( stderr, "\n" );
716 printf( _("# extended LDIF\n") );
717 } else if ( ldif < 3 ) {
718 printf( _("version: %d\n\n"), 1 );
723 printf(_("# LDAPv%d\n"), protocol);
724 printf(_("# base <%s> with scope %s\n"),
725 base ? base : "", (scope == LDAP_SCOPE_BASE) ? "base"
726 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"));
727 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
729 printf(_("# requesting: "));
731 if ( attrs == NULL ) {
734 for ( i = 0; attrs[ i ] != NULL; ++i ) {
735 printf( "%s ", attrs[ i ] );
740 printf(_("\n# with manageDSAit %scontrol"),
741 manageDSAit > 1 ? _("critical ") : "" );
744 printf(_("\n# with noop %scontrol"),
745 noop > 1 ? _("critical ") : "" );
748 printf(_("\n# with subentries %scontrol: %s"),
749 subentries < 0 ? _("critical ") : "",
750 abs(subentries) == 1 ? "false" : "true" );
752 if ( valuesReturnFilter ) {
753 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
754 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
756 #ifdef LDAP_CONTROL_PAGEDRESULTS
758 printf(_("\n# with pagedResults %scontrol: size=%d"),
759 (pagedResults > 1) ? _("critical ") : "",
764 printf( _("\n#\n\n") );
767 if ( infile == NULL ) {
768 rc = dosearch( ld, base, scope, NULL, filtpattern,
769 attrs, attrsonly, NULL, NULL, NULL, -1 );
774 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
775 line[ strlen( line ) - 1 ] = '\0';
781 rc = dosearch( ld, base, scope, filtpattern, line,
782 attrs, attrsonly, NULL, NULL, NULL, -1 );
789 #ifdef LDAP_CONTROL_PAGEDRESULTS
790 if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
792 int i, moreEntries, tmpSize;
794 /* Loop to get the next pages when
795 * enter is pressed on the terminal.
797 if ( entriesLeft > 0 ) {
798 printf( _("Estimate entries: %d\n"), entriesLeft );
800 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
803 moreEntries = getchar();
804 while ( moreEntries != EOF && moreEntries != '\n' ) {
805 if ( i < (int)sizeof(buf) - 1 ) {
806 buf[i] = moreEntries;
809 moreEntries = getchar();
813 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
814 int num = sscanf( buf, "%d", &tmpSize );
816 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
820 pageSize = (ber_int_t)tmpSize;
827 ldap_unbind_ext( ld, NULL, NULL );
828 #ifdef HAVE_CYRUS_SASL
832 ldap_pvt_tls_destroy();
846 LDAPControl **sctrls,
847 LDAPControl **cctrls,
848 struct timeval *timeout,
858 LDAPMessage *res, *msg;
861 struct berval *retdata = NULL;
862 int nresponses_psearch = -1;
863 int cancel_msgid = -1;
865 if( filtpatt != NULL ) {
866 filter = malloc( strlen( filtpatt ) + strlen( value ) );
867 if( filter == NULL ) {
872 sprintf( filter, filtpatt, value );
875 fprintf( stderr, _("filter: %s\n"), filter );
879 printf( _("#\n# filter: %s\n#\n"), filter );
890 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
891 sctrls, cctrls, timeout, sizelimit, &msgid );
893 if ( filtpatt != NULL ) {
897 if( rc != LDAP_SUCCESS ) {
898 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
899 prog, ldap_err2string( rc ), rc );
903 nresponses = nentries = nreferences = nextended = npartial = 0;
907 while ((rc = ldap_result( ld, LDAP_RES_ANY,
908 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
912 (void) ldap_sort_entries( ld, &res,
913 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
916 for ( msg = ldap_first_message( ld, res );
918 msg = ldap_next_message( ld, msg ) )
920 if ( nresponses++ ) putchar('\n');
921 if ( nresponses_psearch >= 0 )
922 nresponses_psearch++;
924 switch( ldap_msgtype( msg ) ) {
925 case LDAP_RES_SEARCH_ENTRY:
927 print_entry( ld, msg, attrsonly );
930 case LDAP_RES_SEARCH_REFERENCE:
932 print_reference( ld, msg );
935 case LDAP_RES_EXTENDED:
937 print_extended( ld, msg );
939 if( ldap_msgid( msg ) == 0 ) {
940 /* unsolicited extended operation */
944 if ( cancel_msgid != -1 &&
945 cancel_msgid == ldap_msgid( msg ) ) {
946 printf(_("Cancelled \n"));
947 printf(_("cancel_msgid = %d\n"), cancel_msgid);
952 case LDAP_RES_SEARCH_RESULT:
953 rc = print_result( ld, msg, 1 );
954 #ifdef LDAP_CONTROL_PAGEDRESULTS
955 if ( pageSize != 0 ) {
956 rc = parse_page_control( ld, msg, &cookie );
960 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
966 case LDAP_RES_INTERMEDIATE:
968 ldap_parse_intermediate( ld, msg,
969 &retoid, &retdata, NULL, 0 );
971 nresponses_psearch = 0;
973 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
974 printf(_("SyncInfo Received\n"));
975 ldap_memfree( retoid );
976 ber_bvfree( retdata );
980 print_partial( ld, msg );
981 ldap_memfree( retoid );
982 ber_bvfree( retdata );
986 if ( ldapsync && sync_slimit != -1 &&
987 nresponses_psearch >= sync_slimit ) {
988 BerElement *msgidber = NULL;
989 struct berval *msgidvalp = NULL;
990 msgidber = ber_alloc_t(LBER_USE_DER);
991 ber_printf(msgidber, "{i}", msgid);
992 ber_flatten(msgidber, &msgidvalp);
993 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
994 msgidvalp, NULL, NULL, &cancel_msgid);
995 nresponses_psearch = -1;
1003 ldap_perror( ld, "ldap_result" );
1008 ldap_msgfree( res );
1009 #ifdef LDAP_CONTROL_PAGEDRESULTS
1010 if ( pageSize != 0 ) {
1011 npagedresponses = npagedresponses + nresponses;
1012 npagedentries = npagedentries + nentries;
1013 npagedreferences = npagedreferences + nreferences;
1014 npagedextended = npagedextended + nextended;
1015 npagedpartial = npagedpartial + npartial;
1016 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1017 printf( _("\n# numResponses: %d\n"), npagedresponses );
1018 if( nentries ) printf( _("# numEntries: %d\n"), npagedentries );
1019 if( nextended ) printf( _("# numExtended: %d\n"), npagedextended );
1020 if( npartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1021 if( nreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1026 printf( _("\n# numResponses: %d\n"), nresponses );
1027 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1028 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1029 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1030 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1037 /* This is the original version, the old way of doing things. */
1045 char tmpfname[ 256 ];
1048 BerElement *ber = NULL;
1049 struct berval **bvals;
1050 LDAPControl **ctrls = NULL;
1053 dn = ldap_get_dn( ld, entry );
1057 ufn = ldap_dn2ufn( dn );
1058 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1060 write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1062 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1064 if( rc != LDAP_SUCCESS ) {
1065 fprintf(stderr, _("print_entry: %d\n"), rc );
1066 ldap_perror( ld, "ldap_get_entry_controls" );
1067 exit( EXIT_FAILURE );
1071 print_ctrls( ctrls );
1072 ldap_controls_free( ctrls );
1077 ufn = ldap_dn2ufn( dn );
1079 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1082 if( ufn != NULL ) ldap_memfree( ufn );
1085 for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1086 a = ldap_next_attribute( ld, entry, ber ) )
1089 write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1091 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1092 for ( i = 0; bvals[i] != NULL; i++ ) {
1093 if ( vals2tmp > 1 || ( vals2tmp && ldif_is_not_printable(
1094 bvals[i]->bv_val, bvals[i]->bv_len ) ))
1097 /* write value to file */
1098 snprintf( tmpfname, sizeof tmpfname,
1099 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1103 tmpfd = mkstemp( tmpfname );
1110 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1115 if ( fwrite( bvals[ i ]->bv_val,
1116 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1125 snprintf( url, sizeof url, "%s%s", urlpre,
1126 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1129 write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1132 write_ldif( LDIF_PUT_VALUE, a,
1133 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1136 ber_bvecfree( bvals );
1146 /* This is the proposed new way of doing things.
1147 * It is more efficient, but the API is non-standard.
1156 char tmpfname[ 256 ];
1159 BerElement *ber = NULL;
1160 struct berval bv, *bvals, **bvp = &bvals;
1161 LDAPControl **ctrls = NULL;
1164 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1167 ufn = ldap_dn2ufn( bv.bv_val );
1168 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1170 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1172 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1173 if( rc != LDAP_SUCCESS ) {
1174 fprintf(stderr, _("print_entry: %d\n"), rc );
1175 ldap_perror( ld, "ldap_get_entry_controls" );
1176 exit( EXIT_FAILURE );
1180 print_ctrls( ctrls );
1181 ldap_controls_free( ctrls );
1186 ufn = ldap_dn2ufn( bv.bv_val );
1188 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1191 if( ufn != NULL ) ldap_memfree( ufn );
1193 if ( attrsonly ) bvp = NULL;
1195 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1197 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1199 if (bv.bv_val == NULL) break;
1202 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1204 } else if ( bvals ) {
1205 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1206 if ( vals2tmp > 1 || ( vals2tmp
1207 && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1210 /* write value to file */
1211 snprintf( tmpfname, sizeof tmpfname,
1212 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1213 tmpdir, bv.bv_val );
1216 tmpfd = mkstemp( tmpfname );
1223 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1228 if ( fwrite( bvals[ i ].bv_val,
1229 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1238 snprintf( url, sizeof url, "%s%s", urlpre,
1239 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1242 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1245 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1246 bvals[ i ].bv_val, bvals[ i ].bv_len );
1249 ber_memfree( bvals );
1259 static void print_reference(
1261 LDAPMessage *reference )
1265 LDAPControl **ctrls;
1268 printf(_("# search reference\n"));
1271 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1273 if( rc != LDAP_SUCCESS ) {
1274 ldap_perror(ld, "ldap_parse_reference");
1275 exit( EXIT_FAILURE );
1280 for( i=0; refs[i] != NULL; i++ ) {
1281 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1282 "ref", refs[i], strlen(refs[i]) );
1284 ber_memvfree( (void **) refs );
1288 print_ctrls( ctrls );
1289 ldap_controls_free( ctrls );
1293 static void print_extended(
1295 LDAPMessage *extended )
1298 char *retoid = NULL;
1299 struct berval *retdata = NULL;
1302 printf(_("# extended result response\n"));
1305 rc = ldap_parse_extended_result( ld, extended,
1306 &retoid, &retdata, 0 );
1308 if( rc != LDAP_SUCCESS ) {
1309 ldap_perror(ld, "ldap_parse_extended_result");
1310 exit( EXIT_FAILURE );
1314 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1315 "extended", retoid, retoid ? strlen(retoid) : 0 );
1317 ber_memfree( retoid );
1321 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1322 "data", retdata->bv_val, retdata->bv_len );
1324 ber_bvfree( retdata );
1327 print_result( ld, extended, 0 );
1330 static void print_partial(
1332 LDAPMessage *partial )
1335 char *retoid = NULL;
1336 struct berval *retdata = NULL;
1337 LDAPControl **ctrls = NULL;
1340 printf(_("# extended partial response\n"));
1343 rc = ldap_parse_intermediate( ld, partial,
1344 &retoid, &retdata, &ctrls, 0 );
1346 if( rc != LDAP_SUCCESS ) {
1347 ldap_perror(ld, "ldap_parse_intermediate");
1348 exit( EXIT_FAILURE );
1352 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1353 "partial", retoid, retoid ? strlen(retoid) : 0 );
1356 ber_memfree( retoid );
1360 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1361 "data", retdata->bv_val, retdata->bv_len );
1364 ber_bvfree( retdata );
1368 print_ctrls( ctrls );
1369 ldap_controls_free( ctrls );
1373 static int print_result(
1375 LDAPMessage *result, int search )
1379 char *matcheddn = NULL;
1382 LDAPControl **ctrls = NULL;
1386 printf(_("# search result\n"));
1389 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1393 rc = ldap_parse_result( ld, result,
1394 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1396 if( rc != LDAP_SUCCESS ) {
1397 ldap_perror(ld, "ldap_parse_result");
1398 exit( EXIT_FAILURE );
1403 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1405 } else if ( err != LDAP_SUCCESS ) {
1406 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1412 write_ldif( LDIF_PUT_VALUE,
1413 "matchedDN", matcheddn, strlen(matcheddn) );
1415 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1419 ber_memfree( matcheddn );
1425 write_ldif( LDIF_PUT_TEXT, "text",
1426 text, strlen(text) );
1428 fprintf( stderr, _("Additional information: %s\n"), text );
1432 ber_memfree( text );
1437 for( i=0; refs[i] != NULL; i++ ) {
1439 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1441 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1445 ber_memvfree( (void **) refs );
1449 print_ctrls( ctrls );
1450 ldap_controls_free( ctrls );
1456 static void print_ctrls(
1457 LDAPControl **ctrls )
1460 for(i=0; ctrls[i] != NULL; i++ ) {
1461 /* control: OID criticality base64value */
1462 struct berval *b64 = NULL;
1467 len += strlen( ctrls[i]->ldctl_oid );
1469 /* add enough for space after OID and the critical value itself */
1470 len += ctrls[i]->ldctl_iscritical
1471 ? sizeof("true") : sizeof("false");
1473 /* convert to base64 */
1474 if( ctrls[i]->ldctl_value.bv_len ) {
1475 b64 = ber_memalloc( sizeof(struct berval) );
1477 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1478 ctrls[i]->ldctl_value.bv_len ) + 1;
1479 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1481 b64->bv_len = lutil_b64_ntop(
1482 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1483 ctrls[i]->ldctl_value.bv_len,
1484 b64->bv_val, b64->bv_len );
1488 len += 1 + b64->bv_len;
1491 str = malloc( len + 1 );
1493 strcpy( str, ": " );
1497 strcat( str, ctrls[i]->ldctl_oid );
1498 strcat( str, ctrls[i]->ldctl_iscritical
1499 ? " true" : " false" );
1503 strcat(str, b64->bv_val );
1507 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1508 "control", str, len );
1517 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1521 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1525 fputs( ldif, stdout );
1526 ber_memfree( ldif );
1532 #ifdef LDAP_CONTROL_PAGEDRESULTS
1536 LDAPMessage *result,
1537 struct berval *cookie )
1541 LDAPControl **ctrl = NULL;
1542 LDAPControl *ctrlp = NULL;
1545 struct berval servercookie = { 0, NULL };
1547 rc = ldap_parse_result( ld, result,
1548 &err, NULL, NULL, NULL, &ctrl, 0 );
1550 if( rc != LDAP_SUCCESS ) {
1551 ldap_perror(ld, "ldap_parse_result");
1552 exit( EXIT_FAILURE );
1555 if ( err != LDAP_SUCCESS ) {
1556 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1560 /* Parse the control value
1561 * searchResult ::= SEQUENCE {
1562 * size INTEGER (0..maxInt),
1563 * -- result set size estimate from server - unused
1564 * cookie OCTET STRING
1568 ber = ber_init( &ctrlp->ldctl_value );
1569 if ( ber == NULL ) {
1570 fprintf( stderr, _("Internal error.\n") );
1571 return EXIT_FAILURE;
1574 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1575 ber_dupbv( cookie, &servercookie );
1576 (void) ber_free( ber, 1 );
1578 if( tag == LBER_ERROR ) {
1580 _("Paged results response control could not be decoded.\n") );
1581 return EXIT_FAILURE;
1584 if( entriesLeft < 0 ) {
1586 _("Invalid entries estimate in paged results response.\n") );
1587 return EXIT_FAILURE;
1590 ldap_controls_free( ctrl );
1593 morePagedResults = 0;