3 * Copyright 1998-2003 The OpenLDAP Foundation, All Rights Reserved.
4 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
11 #include <ac/stdlib.h>
14 #include <ac/string.h>
15 #include <ac/unistd.h>
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
33 #include "lutil_ldap.h"
34 #include "ldap_defaults.h"
40 static int scope = LDAP_SCOPE_SUBTREE;
41 static int deref = -1;
43 static int timelimit = -1;
44 static int sizelimit = -1;
46 static char *def_tmpdir;
47 static char *def_urlpre;
54 "usage: %s [options] [filter [attributes...]]\nwhere:\n"
55 " filter\tRFC-2254 compliant LDAP search filter\n"
56 " attributes\twhitespace-separated list of attribute descriptions\n"
57 " which may include:\n"
58 " 1.1 no attributes\n"
59 " * all user attributes\n"
60 " + all operational attributes\n"
63 " -a deref one of never (default), always, search, or find\n"
64 " -A retrieve attribute names only (no values)\n"
65 " -b basedn base dn for search\n"
66 " -E [!]<ctrl>[=<ctrlparam>] search controls (! indicates criticality)\n"
67 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
68 " [!]domainScope (domain scope)\n"
70 " [!]mv=<filter> (matched values filter)\n"
71 #ifdef LDAP_CONTROL_PAGEDRESULTS
72 " [!]pr=<size> (paged results)\n"
74 #ifdef LDAP_CONTROL_SUBENTRIES
75 " [!]subentries[=true|false] (subentries)\n"
77 #ifdef LDAP_CLIENT_UPDATE
78 " [!]lcup=p/<cint>/<cookie>/<slimit> (LDAP client update)\n"
80 * " s/<cint>/<cookie> (LDAP client update)\n"
81 * " sp/<cint>/<cookie>/<slimit>\n"
85 " [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"
86 " rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"
88 " -F prefix URL prefix for files (default: %s)\n"
89 " -l limit time limit (in seconds) for search\n"
90 " -L print responses in LDIFv1 format\n"
91 " -LL print responses in LDIF format without comments\n"
92 " -LLL print responses in LDIF format without comments\n"
94 " -s scope one of base, one, or sub (search scope)\n"
95 " -S attr sort the results by attribute `attr'\n"
96 " -t write binary values to files in temporary directory\n"
97 " -tt write all values to files in temporary directory\n"
98 " -T path write files to directory specified by path (default: %s)\n"
99 " -u include User Friendly entry names in the output\n"
100 " -z limit size limit (in entries) for search\n"
101 , prog, def_urlpre, def_tmpdir );
103 exit( EXIT_FAILURE );
106 static void print_entry LDAP_P((
111 static void print_reference(
113 LDAPMessage *reference );
115 static void print_extended(
117 LDAPMessage *extended );
119 static void print_partial(
121 LDAPMessage *partial );
123 static int print_result(
128 static void print_ctrls(
129 LDAPControl **ctrls );
131 static int write_ldif LDAP_P((
137 static int dosearch LDAP_P((
145 LDAPControl **sctrls,
146 LDAPControl **cctrls,
147 struct timeval *timeout,
150 static char *tmpdir = NULL;
151 static char *urlpre = NULL;
152 static char *base = NULL;
153 static char *sortattr = NULL;
154 static int includeufn, vals2tmp = 0, ldif = 0;
156 static int subentries = 0, valuesReturnFilter = 0;
157 static char *vrFilter = NULL;
159 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
160 static int domainScope = 0;
163 #if defined(LDAP_CLIENT_UPDATE) || defined(LDAP_SYNC)
165 static int ldapsync = 0;
168 #ifdef LDAP_CLIENT_UPDATE
169 static int lcup_cint = 0;
170 static struct berval lcup_cookie = { 0, NULL };
171 static int lcup_slimit = -1;
175 static struct berval sync_cookie = { 0, NULL };
176 static int sync_slimit = -1;
179 #ifdef LDAP_CONTROL_PAGEDRESULTS
180 static int pagedResults = 0;
181 static ber_int_t pageSize = 0;
182 static ber_int_t entriesLeft = 0;
183 static ber_int_t morePagedResults = 1;
184 static struct berval cookie = { 0, NULL };
185 static int npagedresponses;
186 static int npagedentries;
187 static int npagedreferences;
188 static int npagedextended;
189 static int npagedpartial;
191 static int parse_page_control(
194 struct berval *cookie );
202 if (*LDAP_DIRSEP != '/') {
203 for (p = url; *p; p++) {
204 if (*p == *LDAP_DIRSEP)
211 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
212 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
215 handle_private_option( int i )
218 char *control, *cvalue;
220 case 'a': /* set alias deref option */
221 if ( strcasecmp( optarg, "never" ) == 0 ) {
222 deref = LDAP_DEREF_NEVER;
223 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
224 deref = LDAP_DEREF_SEARCHING;
225 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
226 deref = LDAP_DEREF_FINDING;
227 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
228 deref = LDAP_DEREF_ALWAYS;
230 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
234 case 'A': /* retrieve attribute names only -- no values */
237 case 'b': /* search base */
238 base = strdup( optarg );
240 case 'E': /* search controls */
241 if( protocol == LDAP_VERSION2 ) {
242 fprintf( stderr, "%s: -E incompatible with LDAPv%d\n",
244 exit( EXIT_FAILURE );
247 /* should be extended to support comma separated list of
248 * [!]key[=value] parameters, e.g. -E !foo,bar=567
253 if( optarg[0] == '!' ) {
258 control = strdup( optarg );
259 if ( (cvalue = strchr( control, '=' )) != NULL ) {
263 if ( strcasecmp( control, "mv" ) == 0 ) {
264 /* ValuesReturnFilter control */
265 if( valuesReturnFilter ) {
266 fprintf( stderr, "ValuesReturnFilter previously specified\n");
267 exit( EXIT_FAILURE );
269 valuesReturnFilter= 1 + crit;
271 if ( cvalue == NULL ) {
273 "missing filter in ValuesReturnFilter control\n");
274 exit( EXIT_FAILURE );
278 protocol = LDAP_VERSION3;
280 #ifdef LDAP_CONTROL_PAGEDRESULTS
281 } else if ( strcasecmp( control, "pr" ) == 0 ) {
283 /* PagedResults control */
284 if ( pagedResults != 0 ) {
285 fprintf( stderr, "PagedResultsControl previously specified\n" );
286 exit( EXIT_FAILURE );
289 num = sscanf( cvalue, "%d", &tmp );
291 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", cvalue);
292 exit( EXIT_FAILURE );
295 pageSize = (ber_int_t) tmp;
296 pagedResults = 1 + crit;
299 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
300 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
303 "domainScope control previously specified\n");
304 exit( EXIT_FAILURE );
306 if( cvalue != NULL ) {
308 "domainScope: no control value expected\n" );
312 domainScope = 1 + crit;
314 #ifdef LDAP_CONTROL_SUBENTRIES
315 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
317 fprintf( stderr, "subentries control previously specified\n");
318 exit( EXIT_FAILURE );
320 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
322 } else if ( strcasecmp( cvalue, "false") == 0 ) {
326 "subentries control value \"%s\" invalid\n",
328 exit( EXIT_FAILURE );
330 if( crit ) subentries *= -1;
333 #ifdef LDAP_CLIENT_UPDATE
334 } else if ( strcasecmp( control, "lcup" ) == 0 ) {
338 fprintf( stderr, "client update control previously specified\n");
339 exit( EXIT_FAILURE );
341 if ( ldapsync != -1 ) {
342 fprintf( stderr, "ldap sync control previously specified\n");
343 exit( EXIT_FAILURE );
345 if ( cvalue == NULL ) {
347 "missing specification of client update control\n");
348 exit( EXIT_FAILURE );
350 if ( strncasecmp( cvalue, "p", 1 ) == 0 ) {
351 lcup = LDAP_CUP_PERSIST_ONLY;
352 cvalue = strchr( cvalue, '/' );
354 cookiep = strchr( cvalue, '/' );
356 lcup_cint = atoi( cvalue );
358 slimitp = strchr( cvalue, '/' );
360 while ( isspace( *cookiep ) ) cookiep++;
361 ber_str2bv( cookiep, 0, 0, &lcup_cookie );
362 lcup_slimit = atoi( slimitp );
364 } else if ( strncasecmp( cvalue, "s", 1 ) == 0 ) {
365 lcup = LDAP_CUP_SYNC_ONLY;
367 cookiep = strchr( cvalue, '/' );
369 lcup_cint = atoi( cvalue );
370 ber_str2bv( cookiep, 0, 0, &lcup_cookie );
371 } else if ( strncasecmp( cvalue, "sp", 2 ) == 0 ) {
372 lcup = LDAP_CUP_SYNC_AND_PERSIST;
374 cookiep = strchr( cvalue, '/' );
376 lcup_cint = atoi( cvalue );
378 slimitp = strchr( cvalue, '/' );
380 ber_str2bv( cookiep, 0, 0, &lcup_cookie );
381 lcup_slimit = atoi( slimitp );
385 "client update control value \"%s\" invalid\n",
387 exit( EXIT_FAILURE );
389 if ( crit ) lcup *= -1;
393 } else if ( strcasecmp( control, "sync" ) == 0 ) {
397 fprintf( stderr, "ldap sync control previously specified\n" );
398 exit( EXIT_FAILURE );
401 fprintf( stderr, "client update control previously specified\n" );
402 exit( EXIT_FAILURE );
404 if ( cvalue == NULL ) {
406 "missing specification of ldap sync control\n");
407 exit( EXIT_FAILURE );
409 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
410 ldapsync = LDAP_SYNC_REFRESH_ONLY;
411 cookiep = strchr( cvalue, '/' );
412 if ( cookiep != NULL ) {
414 if ( *cookiep != '\0' ) {
415 ber_str2bv( cookiep, 0, 0, &sync_cookie );
418 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
419 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
420 cookiep = strchr( cvalue, '/' );
421 if ( cookiep != NULL ) {
425 slimitp = strchr( cvalue, '/' );
426 if ( slimitp != NULL ) {
429 if ( cookiep != NULL && *cookiep != '\0' )
430 ber_str2bv( cookiep, 0, 0, &sync_cookie );
431 if ( slimitp != NULL && *slimitp != '\0' )
432 sync_slimit = atoi( slimitp );
435 "ldap sync control value \"%s\" invalid\n",
437 exit( EXIT_FAILURE );
439 if ( crit ) ldapsync *= -1;
443 fprintf( stderr, "Invalid control name: %s\n", control );
447 case 'F': /* uri prefix */
448 if( urlpre ) free( urlpre );
449 urlpre = strdup( optarg );
451 case 'l': /* time limit */
452 timelimit = atoi( optarg );
453 if( timelimit < 0 ) {
454 fprintf( stderr, "%s: invalid timelimit (%d) specified\n",
456 exit( EXIT_FAILURE );
459 case 'L': /* print entries in LDIF format */
462 case 's': /* search scope */
463 if ( strcasecmp( optarg, "base" ) == 0 ) {
464 scope = LDAP_SCOPE_BASE;
465 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
466 scope = LDAP_SCOPE_ONELEVEL;
467 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
468 scope = LDAP_SCOPE_SUBTREE;
470 fprintf( stderr, "scope should be base, one, or sub\n" );
474 case 'S': /* sort attribute */
475 sortattr = strdup( optarg );
477 case 't': /* write attribute values to TMPDIR files */
480 case 'T': /* tmpdir */
481 if( tmpdir ) free( tmpdir );
482 tmpdir = strdup( optarg );
484 case 'u': /* include UFN */
487 case 'z': /* size limit */
488 sizelimit = atoi( optarg );
498 private_conn_setup( LDAP *ld )
501 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
503 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
504 exit( EXIT_FAILURE );
506 if (timelimit != -1 &&
507 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
509 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
510 exit( EXIT_FAILURE );
512 if (sizelimit != -1 &&
513 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
515 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
516 exit( EXIT_FAILURE );
522 main( int argc, char **argv )
524 char *filtpattern, **attrs = NULL, line[BUFSIZ];
528 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
529 #ifdef LDAP_CLIENT_UPDATE
530 BerElement *cuber = NULL;
531 struct berval *cubvalp = NULL;
535 BerElement *syncber = NULL;
536 struct berval *syncbvalp = NULL;
539 #ifdef LDAP_CONTROL_PAGEDRESULTS
540 npagedresponses = npagedentries = npagedreferences =
541 npagedextended = npagedpartial = 0;
544 prog = lutil_progname( "ldapsearch", argc, argv );
546 lutil_log_initialize(argc, argv);
548 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
549 (def_tmpdir = getenv("TMP")) == NULL &&
550 (def_tmpdir = getenv("TEMP")) == NULL )
552 def_tmpdir = LDAP_TMPDIR;
556 def_tmpdir = LDAP_TMPDIR;
558 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
560 if( def_urlpre == NULL ) {
565 sprintf( def_urlpre, "file:///%s/",
566 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
568 urlize( def_urlpre );
570 tool_args( argc, argv );
572 if (( argc - optind < 1 ) ||
573 ( *argv[optind] != '(' /*')'*/ &&
574 ( strchr( argv[optind], '=' ) == NULL ) ) )
576 filtpattern = "(objectclass=*)";
578 filtpattern = strdup( argv[optind++] );
581 if ( argv[optind] != NULL ) {
582 attrs = &argv[optind];
585 if ( infile != NULL ) {
586 if ( infile[0] == '-' && infile[1] == '\0' ) {
588 } else if (( fp = fopen( infile, "r" )) == NULL ) {
594 if ( tmpdir == NULL ) {
597 if ( urlpre == NULL )
601 if( urlpre == NULL ) {
602 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
604 if( urlpre == NULL ) {
609 sprintf( urlpre, "file:///%s/",
610 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
618 ld = tool_conn_setup( 0, &private_conn_setup );
620 if ( pw_file || want_bindpw ) {
622 rc = lutil_get_filed_password( pw_file, &passwd );
623 if( rc ) return EXIT_FAILURE;
625 passwd.bv_val = getpassphrase( "Enter LDAP Password: " );
626 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
633 if ( manageDSAit || noop || subentries || valuesReturnFilter
634 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
637 #ifdef LDAP_CONTROL_PAGEDRESULTS
640 #ifdef LDAP_CLIENT_UPDATE
651 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
653 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
654 c[i].ldctl_value.bv_val = NULL;
655 c[i].ldctl_value.bv_len = 0;
656 c[i].ldctl_iscritical = domainScope > 1;
661 #ifdef LDAP_CONTROL_SUBENTRIES
663 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
667 err = ber_printf( seber, "{b}", abs(subentries) == 1 ? 0 : 1 );
669 ber_free( seber, 1 );
670 fprintf( stderr, "Subentries control encoding error!\n" );
674 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
678 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
679 c[i].ldctl_iscritical = subentries < 1;
684 #ifdef LDAP_CLIENT_UPDATE
686 if (( cuber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
690 if ( lcup_cookie.bv_len == 0 ) {
691 err = ber_printf( cuber, "{ei}", abs(lcup), lcup_cint );
693 err = ber_printf( cuber, "{ei{sO}}", abs(lcup), lcup_cint,
694 LDAP_CUP_COOKIE_OID, &lcup_cookie );
697 if ( err == LBER_ERROR ) {
698 ber_free( cuber, 1 );
699 fprintf( stderr, "client update control encoding error!\n" );
703 if ( ber_flatten( cuber, &cubvalp ) == LBER_ERROR ) {
707 c[i].ldctl_oid = LDAP_CONTROL_CLIENT_UPDATE;
708 c[i].ldctl_value = (*cubvalp);
709 c[i].ldctl_iscritical = lcup < 0;
716 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
720 if ( sync_cookie.bv_len == 0 ) {
721 err = ber_printf( syncber, "{e}", abs(ldapsync) );
723 err = ber_printf( syncber, "{eO}", abs(ldapsync),
727 if ( err == LBER_ERROR ) {
728 ber_free( syncber, 1 );
729 fprintf( stderr, "ldap sync control encoding error!\n" );
733 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
737 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
738 c[i].ldctl_value = (*syncbvalp);
739 c[i].ldctl_iscritical = ldapsync < 0;
744 if ( valuesReturnFilter ) {
745 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
749 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
750 ber_free( vrber, 1 );
751 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
755 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
759 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
760 c[i].ldctl_iscritical = valuesReturnFilter > 1;
764 #ifdef LDAP_CONTROL_PAGEDRESULTS
765 if ( pagedResults ) {
766 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
770 ber_printf( prber, "{iO}", pageSize, &cookie );
771 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
775 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
776 c[i].ldctl_iscritical = pagedResults > 1;
781 tool_server_controls( ld, c, i );
783 ber_free( seber, 1 );
784 ber_free( vrber, 1 );
785 ber_free( prber, 1 );
789 fprintf( stderr, "filter%s: %s\nrequesting: ",
790 infile != NULL ? " pattern" : "",
793 if ( attrs == NULL ) {
794 fprintf( stderr, "ALL" );
796 for ( i = 0; attrs[ i ] != NULL; ++i ) {
797 fprintf( stderr, "%s ", attrs[ i ] );
800 fprintf( stderr, "\n" );
804 printf( "# extended LDIF\n" );
805 } else if ( ldif < 3 ) {
806 printf( "version: %d\n\n", 1 );
812 "# base <%s> with scope %s\n"
816 base ? base : "", (scope == LDAP_SCOPE_BASE) ? "base"
817 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
818 infile != NULL ? " pattern" : "",
821 if ( attrs == NULL ) {
824 for ( i = 0; attrs[ i ] != NULL; ++i ) {
825 printf( "%s ", attrs[ i ] );
830 printf("\n# with manageDSAit %scontrol",
831 manageDSAit > 1 ? "critical " : "" );
834 printf("\n# with noop %scontrol",
835 noop > 1 ? "critical " : "" );
838 printf("\n# with subentries %scontrol: %s",
839 subentries < 0 ? "critical " : "",
840 abs(subentries) == 1 ? "false" : "true" );
842 if ( valuesReturnFilter ) {
843 printf("\n# with valuesReturnFilter %scontrol: %s",
844 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
846 #ifdef LDAP_CONTROL_PAGEDRESULTS
848 printf("\n# with pagedResults %scontrol: size=%d",
849 (pagedResults > 1) ? "critical " : "",
857 if ( infile == NULL ) {
858 rc = dosearch( ld, base, scope, NULL, filtpattern,
859 attrs, attrsonly, NULL, NULL, NULL, -1 );
864 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
865 line[ strlen( line ) - 1 ] = '\0';
871 rc = dosearch( ld, base, scope, filtpattern, line,
872 attrs, attrsonly, NULL, NULL, NULL, -1 );
879 #ifdef LDAP_CONTROL_PAGEDRESULTS
880 if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
882 int i, moreEntries, tmpSize;
884 /* Loop to get the next pages when
885 * enter is pressed on the terminal.
887 if ( entriesLeft > 0 ) {
888 printf( "Estimate entries: %d\n", entriesLeft );
890 printf( "Press [size] Enter for the next {%d|size} entries.\n",
893 moreEntries = getchar();
894 while ( moreEntries != EOF && moreEntries != '\n' ) {
895 if ( i < (int)sizeof(buf) - 1 ) {
896 buf[i] = moreEntries;
899 moreEntries = getchar();
903 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
904 int num = sscanf( buf, "%d", &tmpSize );
906 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
910 pageSize = (ber_int_t)tmpSize;
930 LDAPControl **sctrls,
931 LDAPControl **cctrls,
932 struct timeval *timeout,
942 LDAPMessage *res, *msg;
946 struct berval *retdata = NULL;
947 int nresponses_psearch = -1;
948 int cancel_msgid = -1;
951 if( filtpatt != NULL ) {
952 filter = malloc( strlen( filtpatt ) + strlen( value ) );
953 if( filter == NULL ) {
958 sprintf( filter, filtpatt, value );
961 fprintf( stderr, "filter: %s\n", filter );
965 printf( "#\n# filter: %s\n#\n", filter );
976 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
977 sctrls, cctrls, timeout, sizelimit, &msgid );
979 if ( filtpatt != NULL ) {
983 if( rc != LDAP_SUCCESS ) {
984 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
985 prog, ldap_err2string( rc ), rc );
989 nresponses = nentries = nreferences = nextended = npartial = 0;
993 while ((rc = ldap_result( ld, LDAP_RES_ANY,
994 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
998 (void) ldap_sort_entries( ld, &res,
999 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1002 for ( msg = ldap_first_message( ld, res );
1004 msg = ldap_next_message( ld, msg ) )
1006 if ( nresponses++ ) putchar('\n');
1008 if ( nresponses_psearch >= 0 )
1009 nresponses_psearch++;
1012 switch( ldap_msgtype( msg ) ) {
1013 case LDAP_RES_SEARCH_ENTRY:
1015 print_entry( ld, msg, attrsonly );
1018 case LDAP_RES_SEARCH_REFERENCE:
1020 print_reference( ld, msg );
1023 case LDAP_RES_EXTENDED:
1025 print_extended( ld, msg );
1027 if( ldap_msgid( msg ) == 0 ) {
1028 /* unsolicited extended operation */
1033 if ( cancel_msgid != -1 &&
1034 cancel_msgid == ldap_msgid( msg ) ) {
1035 printf("Cancelled \n");
1036 printf("cancel_msgid = %d\n", cancel_msgid);
1043 case LDAP_RES_EXTENDED_PARTIAL:
1045 print_partial( ld, msg );
1048 case LDAP_RES_SEARCH_RESULT:
1049 rc = print_result( ld, msg, 1 );
1050 #ifdef LDAP_CONTROL_PAGEDRESULTS
1051 if ( pageSize != 0 ) {
1052 rc = parse_page_control( ld, msg, &cookie );
1056 #ifdef LDAP_CLIENT_UPDATE
1057 if ( lcup == LDAP_CUP_PERSIST_ONLY ||
1058 lcup == LDAP_CUP_SYNC_AND_PERSIST ) {
1062 #if defined(LDAP_CLIENT_UPDATE) && defined(LDAP_SYNC)
1066 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1074 case LDAP_RES_INTERMEDIATE_RESP:
1075 ldap_parse_intermediate_resp_result( ld, msg, &retoid, &retdata, 0 );
1076 nresponses_psearch = 0;
1078 if ( strcmp( retoid, LDAP_SYNC_INFO ) ) {
1079 printf("Unexpected Intermediate Response\n");
1080 ldap_memfree( retoid );
1081 ber_bvfree( retdata );
1084 printf("SyncInfo Received\n");
1085 ldap_memfree( retoid );
1086 ber_bvfree( retdata );
1092 #ifdef LDAP_CLIENT_UPDATE
1093 if ( lcup && lcup_slimit != -1 && nresponses >= lcup_slimit ) {
1094 ldap_abandon (ld, ldap_msgid(msg));
1099 if ( ldapsync && sync_slimit != -1 &&
1100 nresponses_psearch >= sync_slimit ) {
1101 BerElement *msgidber = NULL;
1102 struct berval *msgidvalp = NULL;
1103 msgidber = ber_alloc_t(LBER_USE_DER);
1104 ber_printf(msgidber, "{i}", msgid);
1105 ber_flatten(msgidber, &msgidvalp);
1106 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1107 msgidvalp, NULL, NULL, &cancel_msgid);
1108 nresponses_psearch = -1;
1114 ldap_msgfree( res );
1118 ldap_perror( ld, "ldap_result" );
1123 #ifdef LDAP_CONTROL_PAGEDRESULTS
1124 if ( pageSize != 0 ) {
1125 npagedresponses = npagedresponses + nresponses;
1126 npagedentries = npagedentries + nentries;
1127 npagedreferences = npagedreferences + nreferences;
1128 npagedextended = npagedextended + nextended;
1129 npagedpartial = npagedpartial + npartial;
1130 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1131 printf( "\n# numResponses: %d\n", npagedresponses );
1132 if( nentries ) printf( "# numEntries: %d\n", npagedentries );
1133 if( nextended ) printf( "# numExtended: %d\n", npagedextended );
1134 if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
1135 if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
1140 printf( "\n# numResponses: %d\n", nresponses );
1141 if( nentries ) printf( "# numEntries: %d\n", nentries );
1142 if( nextended ) printf( "# numExtended: %d\n", nextended );
1143 if( npartial ) printf( "# numPartial: %d\n", npartial );
1144 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1151 /* This is the original version, the old way of doing things. */
1159 char tmpfname[ 256 ];
1162 BerElement *ber = NULL;
1163 struct berval **bvals;
1164 LDAPControl **ctrls = NULL;
1167 dn = ldap_get_dn( ld, entry );
1171 ufn = ldap_dn2ufn( dn );
1172 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1174 write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1176 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1178 if( rc != LDAP_SUCCESS ) {
1179 fprintf(stderr, "print_entry: %d\n", rc );
1180 ldap_perror( ld, "ldap_get_entry_controls" );
1181 exit( EXIT_FAILURE );
1185 print_ctrls( ctrls );
1186 ldap_controls_free( ctrls );
1191 ufn = ldap_dn2ufn( dn );
1193 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1196 if( ufn != NULL ) ldap_memfree( ufn );
1199 for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1200 a = ldap_next_attribute( ld, entry, ber ) )
1203 write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1205 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1206 for ( i = 0; bvals[i] != 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",
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, a, url, strlen( url ));
1246 write_ldif( LDIF_PUT_VALUE, a,
1247 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1250 ber_bvecfree( bvals );
1260 /* This is the proposed new way of doing things.
1261 * It is more efficient, but the API is non-standard.
1270 char tmpfname[ 256 ];
1273 BerElement *ber = NULL;
1274 struct berval bv, *bvals, **bvp = &bvals;
1275 LDAPControl **ctrls = NULL;
1278 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1281 ufn = ldap_dn2ufn( bv.bv_val );
1282 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1284 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1286 rc = ldap_int_get_controls( ber, &ctrls );
1288 if( rc != LDAP_SUCCESS ) {
1289 fprintf(stderr, "print_entry: %d\n", rc );
1290 ldap_perror( ld, "ldap_get_entry_controls" );
1291 exit( EXIT_FAILURE );
1295 print_ctrls( ctrls );
1296 ldap_controls_free( ctrls );
1301 ufn = ldap_dn2ufn( bv.bv_val );
1303 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1306 if( ufn != NULL ) ldap_memfree( ufn );
1308 if ( attrsonly ) bvp = NULL;
1310 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1312 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1314 if (bv.bv_val == NULL) break;
1317 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1320 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1321 if ( vals2tmp > 1 || ( vals2tmp
1322 && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1325 /* write value to file */
1326 snprintf( tmpfname, sizeof tmpfname,
1327 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1328 tmpdir, bv.bv_val );
1331 tmpfd = mkstemp( tmpfname );
1338 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1343 if ( fwrite( bvals[ i ].bv_val,
1344 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1353 snprintf( url, sizeof url, "%s%s", urlpre,
1354 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1357 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1360 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1361 bvals[ i ].bv_val, bvals[ i ].bv_len );
1364 ber_memfree( bvals );
1374 static void print_reference(
1376 LDAPMessage *reference )
1380 LDAPControl **ctrls;
1383 printf("# search reference\n");
1386 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1388 if( rc != LDAP_SUCCESS ) {
1389 ldap_perror(ld, "ldap_parse_reference");
1390 exit( EXIT_FAILURE );
1395 for( i=0; refs[i] != NULL; i++ ) {
1396 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1397 "ref", refs[i], strlen(refs[i]) );
1399 ber_memvfree( (void **) refs );
1403 print_ctrls( ctrls );
1404 ldap_controls_free( ctrls );
1408 static void print_extended(
1410 LDAPMessage *extended )
1413 char *retoid = NULL;
1414 struct berval *retdata = NULL;
1417 printf("# extended result response\n");
1420 rc = ldap_parse_extended_result( ld, extended,
1421 &retoid, &retdata, 0 );
1423 if( rc != LDAP_SUCCESS ) {
1424 ldap_perror(ld, "ldap_parse_extended_result");
1425 exit( EXIT_FAILURE );
1429 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1430 "extended", retoid, retoid ? strlen(retoid) : 0 );
1432 ber_memfree( retoid );
1436 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1437 "data", retdata->bv_val, retdata->bv_len );
1439 ber_bvfree( retdata );
1442 print_result( ld, extended, 0 );
1445 static void print_partial(
1447 LDAPMessage *partial )
1450 char *retoid = NULL;
1451 struct berval *retdata = NULL;
1452 LDAPControl **ctrls = NULL;
1455 printf("# extended partial response\n");
1458 rc = ldap_parse_extended_partial( ld, partial,
1459 &retoid, &retdata, &ctrls, 0 );
1461 if( rc != LDAP_SUCCESS ) {
1462 ldap_perror(ld, "ldap_parse_extended_partial");
1463 exit( EXIT_FAILURE );
1467 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1468 "partial", retoid, retoid ? strlen(retoid) : 0 );
1471 ber_memfree( retoid );
1475 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1476 "data", retdata->bv_val, retdata->bv_len );
1479 ber_bvfree( retdata );
1483 print_ctrls( ctrls );
1484 ldap_controls_free( ctrls );
1488 static int print_result(
1490 LDAPMessage *result, int search )
1494 char *matcheddn = NULL;
1497 LDAPControl **ctrls = NULL;
1501 printf("# search result\n");
1504 printf("%s: %d\n", "search", ldap_msgid(result) );
1508 rc = ldap_parse_result( ld, result,
1509 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1511 if( rc != LDAP_SUCCESS ) {
1512 ldap_perror(ld, "ldap_parse_result");
1513 exit( EXIT_FAILURE );
1518 printf( "result: %d %s\n", err, ldap_err2string(err) );
1520 } else if ( err != LDAP_SUCCESS ) {
1521 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1524 if( matcheddn && *matcheddn ) {
1526 write_ldif( LDIF_PUT_VALUE,
1527 "matchedDN", matcheddn, strlen(matcheddn) );
1529 fprintf( stderr, "Matched DN: %s\n", matcheddn );
1532 ber_memfree( matcheddn );
1535 if( text && *text ) {
1537 write_ldif( LDIF_PUT_TEXT, "text",
1538 text, strlen(text) );
1540 fprintf( stderr, "Additional information: %s\n", text );
1543 ber_memfree( text );
1548 for( i=0; refs[i] != NULL; i++ ) {
1550 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1552 fprintf( stderr, "Referral: %s\n", refs[i] );
1556 ber_memvfree( (void **) refs );
1560 print_ctrls( ctrls );
1561 ldap_controls_free( ctrls );
1567 static void print_ctrls(
1568 LDAPControl **ctrls )
1571 for(i=0; ctrls[i] != NULL; i++ ) {
1572 /* control: OID criticality base64value */
1573 struct berval *b64 = NULL;
1578 len += strlen( ctrls[i]->ldctl_oid );
1580 /* add enough for space after OID and the critical value itself */
1581 len += ctrls[i]->ldctl_iscritical
1582 ? sizeof("true") : sizeof("false");
1584 /* convert to base64 */
1585 if( ctrls[i]->ldctl_value.bv_len ) {
1586 b64 = ber_memalloc( sizeof(struct berval) );
1588 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1589 ctrls[i]->ldctl_value.bv_len ) + 1;
1590 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1592 b64->bv_len = lutil_b64_ntop(
1593 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1594 b64->bv_val, b64->bv_len );
1598 len += 1 + b64->bv_len;
1601 str = malloc( len + 1 );
1603 strcpy( str, ": " );
1607 strcat( str, ctrls[i]->ldctl_oid );
1608 strcat( str, ctrls[i]->ldctl_iscritical
1609 ? " true" : " false" );
1613 strcat(str, b64->bv_val );
1617 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1618 "control", str, len );
1627 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1631 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1635 fputs( ldif, stdout );
1636 ber_memfree( ldif );
1642 #ifdef LDAP_CONTROL_PAGEDRESULTS
1646 LDAPMessage *result,
1647 struct berval *cookie )
1651 LDAPControl **ctrl = NULL;
1652 LDAPControl *ctrlp = NULL;
1655 struct berval servercookie = { 0, NULL };
1657 rc = ldap_parse_result( ld, result,
1658 &err, NULL, NULL, NULL, &ctrl, 0 );
1660 if( rc != LDAP_SUCCESS ) {
1661 ldap_perror(ld, "ldap_parse_result");
1662 exit( EXIT_FAILURE );
1665 if ( err != LDAP_SUCCESS ) {
1666 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1670 /* Parse the control value
1671 * searchResult ::= SEQUENCE {
1672 * size INTEGER (0..maxInt),
1673 * -- result set size estimate from server - unused
1674 * cookie OCTET STRING
1678 ber = ber_init( &ctrlp->ldctl_value );
1679 if ( ber == NULL ) {
1680 fprintf( stderr, "Internal error.\n" );
1681 return EXIT_FAILURE;
1684 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1685 ber_dupbv( cookie, &servercookie );
1686 (void) ber_free( ber, 1 );
1688 if( tag == LBER_ERROR ) {
1690 "Paged results response control could not be decoded.\n" );
1691 return EXIT_FAILURE;
1694 if( entriesLeft < 0 ) {
1696 "Invalid entries estimate in paged results response.\n" );
1697 return EXIT_FAILURE;
1700 ldap_controls_free( ctrl );
1703 morePagedResults = 0;