1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2003 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;
86 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
87 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
88 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
89 fprintf( stderr, _(" which may include:\n"));
90 fprintf( stderr, _(" 1.1 no attributes\n"));
91 fprintf( stderr, _(" * all user attributes\n"));
92 fprintf( stderr, _(" + all operational attributes\n"));
95 fprintf( stderr, _("Search options:\n"));
96 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
97 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
98 fprintf( stderr, _(" -b basedn base dn for search\n"));
99 fprintf( stderr, _(" -E [!]<ctrl>[=<ctrlparam>] search controls (! indicates criticality)\n"));
100 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
101 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
103 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
104 #ifdef LDAP_CONTROL_PAGEDRESULTS
105 fprintf( stderr, _(" [!]pr=<size> (paged results)\n"));
107 #ifdef LDAP_CONTROL_SUBENTRIES
108 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
110 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
111 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
112 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
113 fprintf( stderr, _(" -l limit time limit (in seconds) for search\n"));
114 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
115 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
116 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
117 fprintf( stderr, _(" and version\n"));
118 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
119 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
120 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
121 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
122 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
123 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
124 fprintf( stderr, _(" -z limit size limit (in entries) for search\n"));
126 exit( EXIT_FAILURE );
129 static void print_entry LDAP_P((
134 static void print_reference(
136 LDAPMessage *reference );
138 static void print_extended(
140 LDAPMessage *extended );
142 static void print_partial(
144 LDAPMessage *partial );
146 static int print_result(
151 static void print_ctrls(
152 LDAPControl **ctrls );
154 static int write_ldif LDAP_P((
160 static int dosearch LDAP_P((
168 LDAPControl **sctrls,
169 LDAPControl **cctrls,
170 struct timeval *timeout,
173 static char *tmpdir = NULL;
174 static char *urlpre = NULL;
175 static char *base = NULL;
176 static char *sortattr = NULL;
177 static int includeufn, vals2tmp = 0, ldif = 0;
179 static int subentries = 0, valuesReturnFilter = 0;
180 static char *vrFilter = NULL;
182 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
183 static int domainScope = 0;
186 static int ldapsync = 0;
187 static struct berval sync_cookie = { 0, NULL };
188 static int sync_slimit = -1;
190 #ifdef LDAP_CONTROL_PAGEDRESULTS
191 static int pagedResults = 0;
192 static ber_int_t pageSize = 0;
193 static ber_int_t entriesLeft = 0;
194 static ber_int_t morePagedResults = 1;
195 static struct berval cookie = { 0, NULL };
196 static int npagedresponses;
197 static int npagedentries;
198 static int npagedreferences;
199 static int npagedextended;
200 static int npagedpartial;
202 static int parse_page_control(
205 struct berval *cookie );
213 if (*LDAP_DIRSEP != '/') {
214 for (p = url; *p; p++) {
215 if (*p == *LDAP_DIRSEP)
222 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
223 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
226 handle_private_option( int i )
229 char *control, *cvalue;
231 case 'a': /* set alias deref option */
232 if ( strcasecmp( optarg, "never" ) == 0 ) {
233 deref = LDAP_DEREF_NEVER;
234 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
235 deref = LDAP_DEREF_SEARCHING;
236 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
237 deref = LDAP_DEREF_FINDING;
238 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
239 deref = LDAP_DEREF_ALWAYS;
241 fprintf( stderr, _("alias deref should be never, search, find, or always\n") );
245 case 'A': /* retrieve attribute names only -- no values */
248 case 'b': /* search base */
249 base = strdup( optarg );
251 case 'E': /* search controls */
252 if( protocol == LDAP_VERSION2 ) {
253 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
255 exit( EXIT_FAILURE );
258 /* should be extended to support comma separated list of
259 * [!]key[=value] parameters, e.g. -E !foo,bar=567
264 if( optarg[0] == '!' ) {
269 control = strdup( optarg );
270 if ( (cvalue = strchr( control, '=' )) != NULL ) {
274 if ( strcasecmp( control, "mv" ) == 0 ) {
275 /* ValuesReturnFilter control */
276 if( valuesReturnFilter ) {
277 fprintf( stderr, _("ValuesReturnFilter previously specified\n"));
278 exit( EXIT_FAILURE );
280 valuesReturnFilter= 1 + crit;
282 if ( cvalue == NULL ) {
284 _("missing filter in ValuesReturnFilter control\n"));
285 exit( EXIT_FAILURE );
289 protocol = LDAP_VERSION3;
291 #ifdef LDAP_CONTROL_PAGEDRESULTS
292 } else if ( strcasecmp( control, "pr" ) == 0 ) {
294 /* PagedResults control */
295 if ( pagedResults != 0 ) {
296 fprintf( stderr, _("PagedResultsControl previously specified\n") );
297 exit( EXIT_FAILURE );
300 num = sscanf( cvalue, "%d", &tmp );
302 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), cvalue);
303 exit( EXIT_FAILURE );
306 pageSize = (ber_int_t) tmp;
307 pagedResults = 1 + crit;
310 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
311 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
314 _("domainScope control previously specified\n"));
315 exit( EXIT_FAILURE );
317 if( cvalue != NULL ) {
319 _("domainScope: no control value expected\n") );
323 domainScope = 1 + crit;
325 #ifdef LDAP_CONTROL_SUBENTRIES
326 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
328 fprintf( stderr, _("subentries control previously specified\n"));
329 exit( EXIT_FAILURE );
331 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
333 } else if ( strcasecmp( cvalue, "false") == 0 ) {
337 _("subentries control value \"%s\" invalid\n"),
339 exit( EXIT_FAILURE );
341 if( crit ) subentries *= -1;
344 } else if ( strcasecmp( control, "sync" ) == 0 ) {
348 fprintf( stderr, _("ldap sync control previously specified\n") );
349 exit( EXIT_FAILURE );
351 if ( cvalue == NULL ) {
353 _("missing specification of ldap sync control\n"));
354 exit( EXIT_FAILURE );
356 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
357 ldapsync = LDAP_SYNC_REFRESH_ONLY;
358 cookiep = strchr( cvalue, '/' );
359 if ( cookiep != NULL ) {
361 if ( *cookiep != '\0' ) {
362 ber_str2bv( cookiep, 0, 0, &sync_cookie );
365 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
366 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
367 cookiep = strchr( cvalue, '/' );
368 if ( cookiep != NULL ) {
372 slimitp = strchr( cvalue, '/' );
373 if ( slimitp != NULL ) {
376 if ( cookiep != NULL && *cookiep != '\0' )
377 ber_str2bv( cookiep, 0, 0, &sync_cookie );
378 if ( slimitp != NULL && *slimitp != '\0' )
379 sync_slimit = atoi( slimitp );
382 _("ldap sync control value \"%s\" invalid\n"),
384 exit( EXIT_FAILURE );
386 if ( crit ) ldapsync *= -1;
389 fprintf( stderr, _("Invalid control name: %s\n"), control );
393 case 'F': /* uri prefix */
394 if( urlpre ) free( urlpre );
395 urlpre = strdup( optarg );
397 case 'l': /* time limit */
398 timelimit = atoi( optarg );
399 if( timelimit < 0 ) {
400 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
402 exit( EXIT_FAILURE );
405 case 'L': /* print entries in LDIF format */
408 case 's': /* search scope */
409 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
410 scope = LDAP_SCOPE_BASE;
411 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
412 scope = LDAP_SCOPE_ONELEVEL;
413 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
414 || ( strcasecmp( optarg, "children" ) == 0 ))
416 scope = LDAP_SCOPE_SUBORDINATE;
417 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
418 scope = LDAP_SCOPE_SUBTREE;
420 fprintf( stderr, _("scope should be base, one, or sub\n") );
424 case 'S': /* sort attribute */
425 sortattr = strdup( optarg );
427 case 't': /* write attribute values to TMPDIR files */
430 case 'T': /* tmpdir */
431 if( tmpdir ) free( tmpdir );
432 tmpdir = strdup( optarg );
434 case 'u': /* include UFN */
437 case 'z': /* size limit */
438 sizelimit = atoi( optarg );
448 private_conn_setup( LDAP *ld )
451 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
453 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
454 exit( EXIT_FAILURE );
456 if (timelimit != -1 &&
457 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
459 fprintf( stderr, _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
460 exit( EXIT_FAILURE );
462 if (sizelimit != -1 &&
463 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
465 fprintf( stderr, _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
466 exit( EXIT_FAILURE );
472 main( int argc, char **argv )
474 char *filtpattern, **attrs = NULL, line[BUFSIZ];
478 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
480 BerElement *syncber = NULL;
481 struct berval *syncbvalp = NULL;
485 #ifdef LDAP_CONTROL_PAGEDRESULTS
486 npagedresponses = npagedentries = npagedreferences =
487 npagedextended = npagedpartial = 0;
490 prog = lutil_progname( "ldapsearch", argc, argv );
492 lutil_log_initialize(argc, argv);
494 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
495 (def_tmpdir = getenv("TMP")) == NULL &&
496 (def_tmpdir = getenv("TEMP")) == NULL )
498 def_tmpdir = LDAP_TMPDIR;
502 def_tmpdir = LDAP_TMPDIR;
504 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
506 if( def_urlpre == NULL ) {
511 sprintf( def_urlpre, "file:///%s/",
512 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
514 urlize( def_urlpre );
516 tool_args( argc, argv );
518 if (( argc - optind < 1 ) ||
519 ( *argv[optind] != '(' /*')'*/ &&
520 ( strchr( argv[optind], '=' ) == NULL ) ) )
522 filtpattern = "(objectclass=*)";
524 filtpattern = strdup( argv[optind++] );
527 if ( argv[optind] != NULL ) {
528 attrs = &argv[optind];
531 if ( infile != NULL ) {
532 if ( infile[0] == '-' && infile[1] == '\0' ) {
534 } else if (( fp = fopen( infile, "r" )) == NULL ) {
540 if ( tmpdir == NULL ) {
543 if ( urlpre == NULL )
547 if( urlpre == NULL ) {
548 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
550 if( urlpre == NULL ) {
555 sprintf( urlpre, "file:///%s/",
556 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
564 ld = tool_conn_setup( 0, &private_conn_setup );
566 if ( pw_file || want_bindpw ) {
568 rc = lutil_get_filed_password( pw_file, &passwd );
569 if( rc ) return EXIT_FAILURE;
571 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
572 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
579 if ( assertion || authzid || manageDSAit || noop
580 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
583 #ifdef LDAP_CONTROL_PAGEDRESULTS
587 || subentries || valuesReturnFilter )
593 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
595 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
596 c[i].ldctl_value.bv_val = NULL;
597 c[i].ldctl_value.bv_len = 0;
598 c[i].ldctl_iscritical = domainScope > 1;
603 #ifdef LDAP_CONTROL_SUBENTRIES
605 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
609 err = ber_printf( seber, "{b}", abs(subentries) == 1 ? 0 : 1 );
611 ber_free( seber, 1 );
612 fprintf( stderr, _("Subentries control encoding error!\n") );
616 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
620 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
621 c[i].ldctl_iscritical = subentries < 1;
627 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
631 if ( sync_cookie.bv_len == 0 ) {
632 err = ber_printf( syncber, "{e}", abs(ldapsync) );
634 err = ber_printf( syncber, "{eO}", abs(ldapsync),
638 if ( err == LBER_ERROR ) {
639 ber_free( syncber, 1 );
640 fprintf( stderr, _("ldap sync control encoding error!\n") );
644 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
648 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
649 c[i].ldctl_value = (*syncbvalp);
650 c[i].ldctl_iscritical = ldapsync < 0;
654 if ( valuesReturnFilter ) {
655 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
659 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
660 ber_free( vrber, 1 );
661 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
665 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
669 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
670 c[i].ldctl_iscritical = valuesReturnFilter > 1;
674 #ifdef LDAP_CONTROL_PAGEDRESULTS
675 if ( pagedResults ) {
676 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
680 ber_printf( prber, "{iO}", pageSize, &cookie );
681 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
685 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
686 c[i].ldctl_iscritical = pagedResults > 1;
691 tool_server_controls( ld, c, i );
693 ber_free( seber, 1 );
694 ber_free( vrber, 1 );
695 ber_free( prber, 1 );
699 fprintf( stderr, _("filter%s: %s\nrequesting: "),
700 infile != NULL ? _(" pattern") : "",
703 if ( attrs == NULL ) {
704 fprintf( stderr, _("ALL") );
706 for ( i = 0; attrs[ i ] != NULL; ++i ) {
707 fprintf( stderr, "%s ", attrs[ i ] );
710 fprintf( stderr, "\n" );
714 printf( _("# extended LDIF\n") );
715 } else if ( ldif < 3 ) {
716 printf( _("version: %d\n\n"), 1 );
721 printf(_("# LDAPv%d\n"), protocol);
722 printf(_("# base <%s> with scope %s\n"),
724 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
725 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
726 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
728 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
730 printf(_("# requesting: "));
732 if ( attrs == NULL ) {
735 for ( i = 0; attrs[ i ] != NULL; ++i ) {
736 printf( "%s ", attrs[ i ] );
741 printf(_("\n# with manageDSAit %scontrol"),
742 manageDSAit > 1 ? _("critical ") : "" );
745 printf(_("\n# with noop %scontrol"),
746 noop > 1 ? _("critical ") : "" );
749 printf(_("\n# with subentries %scontrol: %s"),
750 subentries < 0 ? _("critical ") : "",
751 abs(subentries) == 1 ? "false" : "true" );
753 if ( valuesReturnFilter ) {
754 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
755 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
757 #ifdef LDAP_CONTROL_PAGEDRESULTS
759 printf(_("\n# with pagedResults %scontrol: size=%d"),
760 (pagedResults > 1) ? _("critical ") : "",
765 printf( _("\n#\n\n") );
768 if ( infile == NULL ) {
769 rc = dosearch( ld, base, scope, NULL, filtpattern,
770 attrs, attrsonly, NULL, NULL, NULL, -1 );
775 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
776 line[ strlen( line ) - 1 ] = '\0';
782 rc = dosearch( ld, base, scope, filtpattern, line,
783 attrs, attrsonly, NULL, NULL, NULL, -1 );
790 #ifdef LDAP_CONTROL_PAGEDRESULTS
791 if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
793 int i, moreEntries, tmpSize;
795 /* Loop to get the next pages when
796 * enter is pressed on the terminal.
798 if ( entriesLeft > 0 ) {
799 printf( _("Estimate entries: %d\n"), entriesLeft );
801 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
804 moreEntries = getchar();
805 while ( moreEntries != EOF && moreEntries != '\n' ) {
806 if ( i < (int)sizeof(buf) - 1 ) {
807 buf[i] = moreEntries;
810 moreEntries = getchar();
814 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
815 int num = sscanf( buf, "%d", &tmpSize );
817 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
821 pageSize = (ber_int_t)tmpSize;
829 #ifdef HAVE_CYRUS_SASL
833 ldap_pvt_tls_destroy();
847 LDAPControl **sctrls,
848 LDAPControl **cctrls,
849 struct timeval *timeout,
859 LDAPMessage *res, *msg;
862 struct berval *retdata = NULL;
863 int nresponses_psearch = -1;
864 int cancel_msgid = -1;
866 if( filtpatt != NULL ) {
867 filter = malloc( strlen( filtpatt ) + strlen( value ) );
868 if( filter == NULL ) {
873 sprintf( filter, filtpatt, value );
876 fprintf( stderr, _("filter: %s\n"), filter );
880 printf( _("#\n# filter: %s\n#\n"), filter );
891 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
892 sctrls, cctrls, timeout, sizelimit, &msgid );
894 if ( filtpatt != NULL ) {
898 if( rc != LDAP_SUCCESS ) {
899 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
900 prog, ldap_err2string( rc ), rc );
904 nresponses = nentries = nreferences = nextended = npartial = 0;
908 while ((rc = ldap_result( ld, LDAP_RES_ANY,
909 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
913 (void) ldap_sort_entries( ld, &res,
914 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
917 for ( msg = ldap_first_message( ld, res );
919 msg = ldap_next_message( ld, msg ) )
921 if ( nresponses++ ) putchar('\n');
922 if ( nresponses_psearch >= 0 )
923 nresponses_psearch++;
925 switch( ldap_msgtype( msg ) ) {
926 case LDAP_RES_SEARCH_ENTRY:
928 print_entry( ld, msg, attrsonly );
931 case LDAP_RES_SEARCH_REFERENCE:
933 print_reference( ld, msg );
936 case LDAP_RES_EXTENDED:
938 print_extended( ld, msg );
940 if( ldap_msgid( msg ) == 0 ) {
941 /* unsolicited extended operation */
945 if ( cancel_msgid != -1 &&
946 cancel_msgid == ldap_msgid( msg ) ) {
947 printf(_("Cancelled \n"));
948 printf(_("cancel_msgid = %d\n"), cancel_msgid);
953 case LDAP_RES_SEARCH_RESULT:
954 rc = print_result( ld, msg, 1 );
955 #ifdef LDAP_CONTROL_PAGEDRESULTS
956 if ( pageSize != 0 ) {
957 rc = parse_page_control( ld, msg, &cookie );
961 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
967 case LDAP_RES_INTERMEDIATE:
969 ldap_parse_intermediate( ld, msg,
970 &retoid, &retdata, NULL, 0 );
972 nresponses_psearch = 0;
974 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
975 printf(_("SyncInfo Received\n"));
976 ldap_memfree( retoid );
977 ber_bvfree( retdata );
981 print_partial( ld, msg );
982 ldap_memfree( retoid );
983 ber_bvfree( retdata );
987 if ( ldapsync && sync_slimit != -1 &&
988 nresponses_psearch >= sync_slimit ) {
989 BerElement *msgidber = NULL;
990 struct berval *msgidvalp = NULL;
991 msgidber = ber_alloc_t(LBER_USE_DER);
992 ber_printf(msgidber, "{i}", msgid);
993 ber_flatten(msgidber, &msgidvalp);
994 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
995 msgidvalp, NULL, NULL, &cancel_msgid);
996 nresponses_psearch = -1;
1000 ldap_msgfree( res );
1004 ldap_perror( ld, "ldap_result" );
1009 ldap_msgfree( res );
1010 #ifdef LDAP_CONTROL_PAGEDRESULTS
1011 if ( pageSize != 0 ) {
1012 npagedresponses = npagedresponses + nresponses;
1013 npagedentries = npagedentries + nentries;
1014 npagedreferences = npagedreferences + nreferences;
1015 npagedextended = npagedextended + nextended;
1016 npagedpartial = npagedpartial + npartial;
1017 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1018 printf( _("\n# numResponses: %d\n"), npagedresponses );
1019 if( nentries ) printf( _("# numEntries: %d\n"), npagedentries );
1020 if( nextended ) printf( _("# numExtended: %d\n"), npagedextended );
1021 if( npartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1022 if( nreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1027 printf( _("\n# numResponses: %d\n"), nresponses );
1028 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1029 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1030 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1031 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1038 /* This is the original version, the old way of doing things. */
1046 char tmpfname[ 256 ];
1049 BerElement *ber = NULL;
1050 struct berval **bvals;
1051 LDAPControl **ctrls = NULL;
1054 dn = ldap_get_dn( ld, entry );
1058 ufn = ldap_dn2ufn( dn );
1059 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1061 write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1063 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1065 if( rc != LDAP_SUCCESS ) {
1066 fprintf(stderr, _("print_entry: %d\n"), rc );
1067 ldap_perror( ld, "ldap_get_entry_controls" );
1068 exit( EXIT_FAILURE );
1072 print_ctrls( ctrls );
1073 ldap_controls_free( ctrls );
1078 ufn = ldap_dn2ufn( dn );
1080 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1083 if( ufn != NULL ) ldap_memfree( ufn );
1086 for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1087 a = ldap_next_attribute( ld, entry, ber ) )
1090 write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1092 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1093 for ( i = 0; bvals[i] != NULL; i++ ) {
1094 if ( vals2tmp > 1 || ( vals2tmp
1095 && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1098 /* write value to file */
1099 snprintf( tmpfname, sizeof tmpfname,
1100 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1104 tmpfd = mkstemp( tmpfname );
1111 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1116 if ( fwrite( bvals[ i ]->bv_val,
1117 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1126 snprintf( url, sizeof url, "%s%s", urlpre,
1127 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1130 write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1133 write_ldif( LDIF_PUT_VALUE, a,
1134 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1137 ber_bvecfree( bvals );
1147 /* This is the proposed new way of doing things.
1148 * It is more efficient, but the API is non-standard.
1157 char tmpfname[ 256 ];
1160 BerElement *ber = NULL;
1161 struct berval bv, *bvals, **bvp = &bvals;
1162 LDAPControl **ctrls = NULL;
1165 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1168 ufn = ldap_dn2ufn( bv.bv_val );
1169 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1171 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1173 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1174 if( rc != LDAP_SUCCESS ) {
1175 fprintf(stderr, _("print_entry: %d\n"), rc );
1176 ldap_perror( ld, "ldap_get_entry_controls" );
1177 exit( EXIT_FAILURE );
1181 print_ctrls( ctrls );
1182 ldap_controls_free( ctrls );
1187 ufn = ldap_dn2ufn( bv.bv_val );
1189 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1192 if( ufn != NULL ) ldap_memfree( ufn );
1194 if ( attrsonly ) bvp = NULL;
1196 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1198 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1200 if (bv.bv_val == NULL) break;
1203 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1205 } else if ( bvals ) {
1206 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1207 if ( vals2tmp > 1 || ( vals2tmp
1208 && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1211 /* write value to file */
1212 snprintf( tmpfname, sizeof tmpfname,
1213 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1214 tmpdir, bv.bv_val );
1217 tmpfd = mkstemp( tmpfname );
1224 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1229 if ( fwrite( bvals[ i ].bv_val,
1230 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1239 snprintf( url, sizeof url, "%s%s", urlpre,
1240 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1243 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1246 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1247 bvals[ i ].bv_val, bvals[ i ].bv_len );
1250 ber_memfree( bvals );
1260 static void print_reference(
1262 LDAPMessage *reference )
1266 LDAPControl **ctrls;
1269 printf(_("# search reference\n"));
1272 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1274 if( rc != LDAP_SUCCESS ) {
1275 ldap_perror(ld, "ldap_parse_reference");
1276 exit( EXIT_FAILURE );
1281 for( i=0; refs[i] != NULL; i++ ) {
1282 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1283 "ref", refs[i], strlen(refs[i]) );
1285 ber_memvfree( (void **) refs );
1289 print_ctrls( ctrls );
1290 ldap_controls_free( ctrls );
1294 static void print_extended(
1296 LDAPMessage *extended )
1299 char *retoid = NULL;
1300 struct berval *retdata = NULL;
1303 printf(_("# extended result response\n"));
1306 rc = ldap_parse_extended_result( ld, extended,
1307 &retoid, &retdata, 0 );
1309 if( rc != LDAP_SUCCESS ) {
1310 ldap_perror(ld, "ldap_parse_extended_result");
1311 exit( EXIT_FAILURE );
1315 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1316 "extended", retoid, retoid ? strlen(retoid) : 0 );
1318 ber_memfree( retoid );
1322 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1323 "data", retdata->bv_val, retdata->bv_len );
1325 ber_bvfree( retdata );
1328 print_result( ld, extended, 0 );
1331 static void print_partial(
1333 LDAPMessage *partial )
1336 char *retoid = NULL;
1337 struct berval *retdata = NULL;
1338 LDAPControl **ctrls = NULL;
1341 printf(_("# extended partial response\n"));
1344 rc = ldap_parse_intermediate( ld, partial,
1345 &retoid, &retdata, &ctrls, 0 );
1347 if( rc != LDAP_SUCCESS ) {
1348 ldap_perror(ld, "ldap_parse_intermediate");
1349 exit( EXIT_FAILURE );
1353 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1354 "partial", retoid, retoid ? strlen(retoid) : 0 );
1357 ber_memfree( retoid );
1361 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1362 "data", retdata->bv_val, retdata->bv_len );
1365 ber_bvfree( retdata );
1369 print_ctrls( ctrls );
1370 ldap_controls_free( ctrls );
1374 static int print_result(
1376 LDAPMessage *result, int search )
1380 char *matcheddn = NULL;
1383 LDAPControl **ctrls = NULL;
1387 printf(_("# search result\n"));
1390 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1394 rc = ldap_parse_result( ld, result,
1395 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1397 if( rc != LDAP_SUCCESS ) {
1398 ldap_perror(ld, "ldap_parse_result");
1399 exit( EXIT_FAILURE );
1404 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1406 } else if ( err != LDAP_SUCCESS ) {
1407 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1413 write_ldif( LDIF_PUT_VALUE,
1414 "matchedDN", matcheddn, strlen(matcheddn) );
1416 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1420 ber_memfree( matcheddn );
1426 write_ldif( LDIF_PUT_TEXT, "text",
1427 text, strlen(text) );
1429 fprintf( stderr, _("Additional information: %s\n"), text );
1433 ber_memfree( text );
1438 for( i=0; refs[i] != NULL; i++ ) {
1440 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1442 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1446 ber_memvfree( (void **) refs );
1450 print_ctrls( ctrls );
1451 ldap_controls_free( ctrls );
1457 static void print_ctrls(
1458 LDAPControl **ctrls )
1461 for(i=0; ctrls[i] != NULL; i++ ) {
1462 /* control: OID criticality base64value */
1463 struct berval *b64 = NULL;
1468 len += strlen( ctrls[i]->ldctl_oid );
1470 /* add enough for space after OID and the critical value itself */
1471 len += ctrls[i]->ldctl_iscritical
1472 ? sizeof("true") : sizeof("false");
1474 /* convert to base64 */
1475 if( ctrls[i]->ldctl_value.bv_len ) {
1476 b64 = ber_memalloc( sizeof(struct berval) );
1478 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1479 ctrls[i]->ldctl_value.bv_len ) + 1;
1480 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1482 b64->bv_len = lutil_b64_ntop(
1483 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1484 ctrls[i]->ldctl_value.bv_len,
1485 b64->bv_val, b64->bv_len );
1489 len += 1 + b64->bv_len;
1492 str = malloc( len + 1 );
1494 strcpy( str, ": " );
1498 strcat( str, ctrls[i]->ldctl_oid );
1499 strcat( str, ctrls[i]->ldctl_iscritical
1500 ? " true" : " false" );
1504 strcat(str, b64->bv_val );
1508 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1509 "control", str, len );
1518 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1522 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1526 fputs( ldif, stdout );
1527 ber_memfree( ldif );
1533 #ifdef LDAP_CONTROL_PAGEDRESULTS
1537 LDAPMessage *result,
1538 struct berval *cookie )
1542 LDAPControl **ctrl = NULL;
1543 LDAPControl *ctrlp = NULL;
1546 struct berval servercookie = { 0, NULL };
1548 rc = ldap_parse_result( ld, result,
1549 &err, NULL, NULL, NULL, &ctrl, 0 );
1551 if( rc != LDAP_SUCCESS ) {
1552 ldap_perror(ld, "ldap_parse_result");
1553 exit( EXIT_FAILURE );
1556 if ( err != LDAP_SUCCESS ) {
1557 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1561 /* Parse the control value
1562 * searchResult ::= SEQUENCE {
1563 * size INTEGER (0..maxInt),
1564 * -- result set size estimate from server - unused
1565 * cookie OCTET STRING
1569 ber = ber_init( &ctrlp->ldctl_value );
1570 if ( ber == NULL ) {
1571 fprintf( stderr, _("Internal error.\n") );
1572 return EXIT_FAILURE;
1575 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1576 ber_dupbv( cookie, &servercookie );
1577 (void) ber_free( ber, 1 );
1579 if( tag == LBER_ERROR ) {
1581 _("Paged results response control could not be decoded.\n") );
1582 return EXIT_FAILURE;
1585 if( entriesLeft < 0 ) {
1587 _("Invalid entries estimate in paged results response.\n") );
1588 return EXIT_FAILURE;
1591 ldap_controls_free( ctrl );
1594 morePagedResults = 0;