]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Update SASL code to reuse context through life of session.
[openldap] / clients / tools / ldapsearch.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2000 The OpenLDAP Foundation, All Rights Reserved.
4  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
5  */
6
7 #include "portable.h"
8
9 #include <stdio.h>
10
11 #include <ac/stdlib.h>
12
13 #include <ac/ctype.h>
14 #include <ac/signal.h>
15 #include <ac/string.h>
16 #include <ac/unistd.h>
17 #include <ac/errno.h>
18 #include <sys/stat.h>
19
20 #ifdef HAVE_FCNTL_H
21 #include <fcntl.h>
22 #endif
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
25 #endif
26 #ifdef HAVE_IO_H
27 #include <io.h>
28 #endif
29
30 #include <ldap.h>
31
32 #include "ldif.h"
33 #include "lutil.h"
34 #include "lutil_ldap.h"
35 #include "ldap_defaults.h"
36
37 static void
38 usage( const char *s )
39 {
40         fprintf( stderr,
41 "usage: %s [options] [filter [attributes...]]\nwhere:\n"
42 "\tfilter\tRFC-2254 compliant LDAP search filter\n"
43 "\tattributes\twhitespace-separated list of attribute descriptions\n"
44 "\t  which may include:\n"
45 "\t\t1.1 -- no attributes\n"
46 "\t\t*   -- all user attributes\n"
47 "\t\t+   -- all operational attributes\n"
48 "options:\n"
49 "\t-a deref\tdereference aliases: never (default), always, search, or find\n"
50 "\t-A\t\tretrieve attribute names only (no values)\n"
51 "\t-b basedn\tbase dn for search\n"
52 "\t-d level\tset LDAP debugging level to `level'\n"
53 "\t-D binddn\tbind DN\n"
54 "\t-E\t\trequest SASL privacy (-EE to make it critical)\n"
55 "\t-f file\t\tperform sequence of searches listed in `file'\n"
56 "\t-h host\t\tLDAP server\n"
57 "\t-I\t\trequest SASL integrity checking (-II to make it\n"
58 "\t\t\tcritical)\n"
59 "\t-k\t\tuse Kerberos authentication\n"
60 "\t-K\t\tlike -k, but do only step 1 of the Kerberos bind\n"
61 "\t-l limit\ttime limit (in seconds) for search\n"
62 "\t-L\t\tprint responses in LDIFv1 format\n"
63 "\t-LL\t\tprint responses in LDIF format without comments\n"
64 "\t-LLL\t\tprint responses in LDIF format without comments\n"
65 "\t\t\tand version\n"
66 "\t-M\t\tenable Manage DSA IT control (-MM to make critical)\n"
67 "\t-n\t\tshow what would be done but don't actually search\n"
68 "\t-O secprops\tSASL security properties\n"
69 "\t-p port\t\tport on LDAP server\n"
70 "\t-P version\tprocotol version (default: 3)\n"
71 "\t-s scope\tone of base, one, or sub (search scope)\n"
72 "\t-S attr\t\tsort the results by attribute `attr'\n"
73 "\t-t\t\twrite binary values to files in temporary directory\n"
74 "\t-tt\t\twrite all values to files in temporary directory\n"
75 "\t-T path\t\twrite files to directory specified by path (default:\n"
76 "\t\t\t\"" LDAP_TMPDIR "\")\n"
77 "\t-u\t\tinclude User Friendly entry names in the output\n"
78 "\t-U user\t\tSASL authentication identity (username)\n"
79 "\t-v\t\trun in verbose mode (diagnostics to standard output)\n"
80 "\t-V prefix\tURL prefix for files (default: \"" LDAP_FILE_URI_PREFIX ")\n"
81 "\t-w passwd\tbind passwd (for simple authentication)\n"
82 "\t-W\t\tprompt for bind passwd\n"
83 "\t-X id\t\tSASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
84 "\t-Y mech\t\tSASL mechanism\n"
85 "\t-z limit\tsize limit (in entries) for search\n"
86 "\t-Z\t\tissue Start TLS request (-ZZ to require successful response)\n"
87 , s );
88
89         exit( EXIT_FAILURE );
90 }
91
92 static void print_entry LDAP_P((
93         LDAP    *ld,
94         LDAPMessage     *entry,
95         int             attrsonly));
96
97 static void print_reference(
98         LDAP *ld,
99         LDAPMessage *reference );
100
101 static void print_extended(
102         LDAP *ld,
103         LDAPMessage *extended );
104
105 static void print_partial(
106         LDAP *ld,
107         LDAPMessage *partial );
108
109 static int print_result(
110         LDAP *ld,
111         LDAPMessage *result,
112         int search );
113
114 static void print_ctrls(
115         LDAPControl **ctrls );
116
117 static int write_ldif LDAP_P((
118         int type,
119         char *name,
120         char *value,
121         ber_len_t vallen ));
122
123 static int dosearch LDAP_P((
124         LDAP    *ld,
125         char    *base,
126         int             scope,
127         char    *filtpatt,
128         char    *value,
129         char    **attrs,
130         int             attrsonly,
131         LDAPControl **sctrls,
132         LDAPControl **cctrls,
133         struct timeval *timelimit,
134         int     sizelimit ));
135
136 static char *tmpdir = NULL;
137 static char *urlpre = NULL;
138
139 static char     *binddn = NULL;
140 static struct berval passwd = { 0, NULL };
141 static char     *base = NULL;
142 static char     *ldaphost = NULL;
143 static int      ldapport = 0;
144 #ifdef HAVE_CYRUS_SASL
145 static char     *sasl_authc_id = NULL;
146 static char     *sasl_authz_id = NULL;
147 static char     *sasl_mech = NULL;
148 static char     *sasl_secprops = NULL;
149 #endif
150 static int      use_tls = 0;
151 static char     *sortattr = NULL;
152 static int      verbose, not, includeufn, vals2tmp, ldif;
153
154 int
155 main( int argc, char **argv )
156 {
157         char            *infile, *filtpattern, **attrs, line[BUFSIZ];
158         FILE            *fp = NULL;
159         int                     rc, i, first, scope, deref, attrsonly, manageDSAit;
160         int                     referrals, timelimit, sizelimit, debug;
161         int             authmethod, version, want_bindpw;
162         LDAP            *ld;
163
164         infile = NULL;
165         debug = verbose = not = vals2tmp = referrals =
166                 attrsonly = manageDSAit = ldif = want_bindpw = 0;
167
168         deref = sizelimit = timelimit = version = -1;
169
170         scope = LDAP_SCOPE_SUBTREE;
171         authmethod = LDAP_AUTH_SIMPLE;
172
173         while (( i = getopt( argc, argv,
174                 "Aa:b:CD:d:f:h:KkLl:MnO:P:p:RS:s:T:tU:uV:vWw:X:Y:Zz:")) != EOF )
175         {
176         switch( i ) {
177         case 'n':       /* do nothing */
178                 ++not;
179                 break;
180         case 'v':       /* verbose mode */
181                 ++verbose;
182                 break;
183         case 'd':
184                 debug |= atoi( optarg );
185                 break;
186         case 'k':       /* use kerberos bind */
187 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
188                 authmethod = LDAP_AUTH_KRBV4;
189 #else
190                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
191                 return( EXIT_FAILURE );
192 #endif
193                 break;
194         case 'K':       /* use kerberos bind, 1st part only */
195 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
196                 authmethod = LDAP_AUTH_KRBV41;
197 #else
198                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
199                 return( EXIT_FAILURE );
200 #endif
201                 break;
202                 break;
203         case 'u':       /* include UFN */
204                 ++includeufn;
205                 break;
206         case 't':       /* write attribute values to TMPDIR files */
207                 ++vals2tmp;
208                 break;
209         case 'M':
210                 /* enable Manage DSA IT */
211                 manageDSAit++;
212                 break;
213         case 'C':
214                 referrals++;
215                 break;
216         case 'R':       /* ignore */
217                 break;
218         case 'A':       /* retrieve attribute names only -- no values */
219                 ++attrsonly;
220                 break;
221         case 'L':       /* print entries in LDIF format */
222                 ++ldif;
223                 break;
224
225         case 's':       /* search scope */
226                 if ( strcasecmp( optarg, "base" ) == 0 ) {
227                 scope = LDAP_SCOPE_BASE;
228                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
229                 scope = LDAP_SCOPE_ONELEVEL;
230                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
231                 scope = LDAP_SCOPE_SUBTREE;
232                 } else {
233                 fprintf( stderr, "scope should be base, one, or sub\n" );
234                 usage( argv[ 0 ] );
235                 }
236                 break;
237
238         case 'a':       /* set alias deref option */
239                 if ( strcasecmp( optarg, "never" ) == 0 ) {
240                 deref = LDAP_DEREF_NEVER;
241                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
242                 deref = LDAP_DEREF_SEARCHING;
243                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
244                 deref = LDAP_DEREF_FINDING;
245                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
246                 deref = LDAP_DEREF_ALWAYS;
247                 } else {
248                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
249                 usage( argv[ 0 ] );
250                 }
251                 break;
252                 
253         case 'T':       /* tmpdir */
254                 if( tmpdir ) free( tmpdir );
255                 tmpdir = strdup( optarg );
256                 break;
257         case 'V':       /* uri prefix */
258                 if( urlpre ) free( urlpre );
259                 urlpre = strdup( optarg );
260                 break;
261         case 'f':       /* input file */
262                 infile = strdup( optarg );
263                 break;
264         case 'h':       /* ldap host */
265                 ldaphost = strdup( optarg );
266                 break;
267         case 'b':       /* search base */
268                 base = strdup( optarg );
269                 break;
270         case 'D':       /* bind DN */
271                 binddn = strdup( optarg );
272                 break;
273         case 'p':       /* ldap port */
274                 ldapport = atoi( optarg );
275                 break;
276         case 'w':       /* bind password */
277                 passwd.bv_val = strdup( optarg );
278                 {
279                         char* p;
280
281                         for( p = optarg; *p == '\0'; p++ ) {
282                                 *p = '*';
283                         }
284                 }
285                 passwd.bv_len = strlen( passwd.bv_val );
286                 break;
287         case 'l':       /* time limit */
288                 timelimit = atoi( optarg );
289                 break;
290         case 'z':       /* size limit */
291                 sizelimit = atoi( optarg );
292                 break;
293         case 'S':       /* sort attribute */
294                 sortattr = strdup( optarg );
295                 break;
296         case 'W':
297                 want_bindpw++;
298                 break;
299         case 'P':
300                 switch( atoi( optarg ) )
301                 {
302                 case 2:
303                         version = LDAP_VERSION2;
304                         break;
305                 case 3:
306                         version = LDAP_VERSION3;
307                         break;
308                 default:
309                         fprintf( stderr, "protocol version should be 2 or 3\n" );
310                         usage( argv[0] );
311                 }
312                 break;
313         case 'O':
314 #ifdef HAVE_CYRUS_SASL
315                 sasl_secprops = strdup( optarg );
316                 authmethod = LDAP_AUTH_SASL;
317 #else
318                 fprintf( stderr, "%s was not compiled with SASL support\n",
319                         argv[0] );
320                 return( EXIT_FAILURE );
321 #endif
322                 break;
323         case 'Y':
324 #ifdef HAVE_CYRUS_SASL
325                 if ( strcasecmp( optarg, "any" ) && strcmp( optarg, "*" ) ) {
326                         sasl_mech = strdup( optarg );
327                 }
328                 authmethod = LDAP_AUTH_SASL;
329 #else
330                 fprintf( stderr, "%s was not compiled with SASL support\n",
331                         argv[0] );
332                 return( EXIT_FAILURE );
333 #endif
334                 break;
335         case 'U':
336 #ifdef HAVE_CYRUS_SASL
337                 sasl_authc_id = strdup( optarg );
338                 authmethod = LDAP_AUTH_SASL;
339 #else
340                 fprintf( stderr, "%s was not compiled with SASL support\n",
341                         argv[0] );
342                 return( EXIT_FAILURE );
343 #endif
344                 break;
345         case 'X':
346 #ifdef HAVE_CYRUS_SASL
347                 sasl_authz_id = strdup( optarg );
348                 authmethod = LDAP_AUTH_SASL;
349 #else
350                 fprintf( stderr, "%s was not compiled with SASL support\n",
351                         argv[0] );
352                 return( EXIT_FAILURE );
353 #endif
354                 break;
355         case 'Z':
356 #ifdef HAVE_TLS
357                 use_tls++;
358 #else
359                 fprintf( stderr, "%s was not compiled with TLS support\n",
360                         argv[0] );
361                 return( EXIT_FAILURE );
362 #endif
363                 break;
364         default:
365                 usage( argv[0] );
366         }
367         }
368
369         if ( ( authmethod == LDAP_AUTH_KRBV4 ) || ( authmethod ==
370                         LDAP_AUTH_KRBV41 ) ) {
371                 if( version > LDAP_VERSION2 ) {
372                         fprintf( stderr, "Kerberos requires LDAPv2\n" );
373                         return( EXIT_FAILURE );
374                 }
375                 version = LDAP_VERSION2;
376         }
377         else if ( authmethod == LDAP_AUTH_SASL ) {
378                 if( version != -1 && version != LDAP_VERSION3 ) {
379                         fprintf( stderr, "SASL requires LDAPv3\n" );
380                         return( EXIT_FAILURE );
381                 }
382                 version = LDAP_VERSION3;
383         }
384
385         if( manageDSAit ) {
386                 if( version != -1 && version != LDAP_VERSION3 ) {
387                         fprintf(stderr, "manage DSA control requires LDAPv3\n");
388                         return EXIT_FAILURE;
389                 }
390                 version = LDAP_VERSION3;
391         }
392
393         if( use_tls ) {
394                 if( version != -1 && version != LDAP_VERSION3 ) {
395                         fprintf(stderr, "Start TLS requires LDAPv3\n");
396                         return EXIT_FAILURE;
397                 }
398                 version = LDAP_VERSION3;
399         }
400
401         if ( argc - optind < 1 ) {
402                 filtpattern = "(objectclass=*)";
403         } else {
404                 filtpattern = strdup( argv[optind++] );
405         }
406
407         if ( argv[optind] == NULL ) {
408                 attrs = NULL;
409         } else if ( sortattr == NULL || *sortattr == '\0' ) {
410                 attrs = &argv[optind];
411         }
412
413         if ( infile != NULL ) {
414                 if ( infile[0] == '-' && infile[1] == '\0' ) {
415                         fp = stdin;
416                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
417                         perror( infile );
418                         return EXIT_FAILURE;
419                 }
420         }
421
422         if( tmpdir == NULL
423                 && (tmpdir = getenv("TMPDIR")) == NULL
424                 && (tmpdir = getenv("TMP")) == NULL
425                 && (tmpdir = getenv("TEMP")) == NULL )
426         {
427                 tmpdir = LDAP_TMPDIR;
428         }
429
430         if( urlpre == NULL ) {
431                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
432
433                 if( urlpre == NULL ) {
434                         perror( "malloc" );
435                         return EXIT_FAILURE;
436                 }
437
438                 sprintf( urlpre, "file:///%s/",
439                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
440
441                 /* urlpre should be URLized.... */
442         }
443
444         if ( debug ) {
445                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
446                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
447                 }
448                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
449                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
450                 }
451                 ldif_debug = debug;
452         }
453
454 #ifdef SIGPIPE
455         (void) SIGNAL( SIGPIPE, SIG_IGN );
456 #endif
457
458         if ( verbose ) {
459                 fprintf( stderr,
460                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
461                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
462                         ldapport );
463         }
464
465         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
466                 perror( "ldap_init" );
467                 return EXIT_FAILURE;
468         }
469
470         if (deref != -1 &&
471                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
472         {
473                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
474                 return EXIT_FAILURE;
475         }
476         if (timelimit != -1 &&
477                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
478         {
479                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
480                 return EXIT_FAILURE;
481         }
482         if (sizelimit != -1 &&
483                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
484         {
485                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
486                 return EXIT_FAILURE;
487         }
488
489         /* referrals */
490         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
491                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
492         {
493                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
494                         referrals ? "on" : "off" );
495                 return EXIT_FAILURE;
496         }
497
498         if (version == -1 ) {
499                 version = 3;
500         }
501
502         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
503                 != LDAP_OPT_SUCCESS )
504         {
505                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
506                         version );
507                 return EXIT_FAILURE;
508         }
509
510         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
511                 if ( use_tls > 1 ) {
512                         ldap_perror( ld, "ldap_start_tls" );
513                         return EXIT_FAILURE;
514                 }
515                 fprintf( stderr, "WARNING: could not start TLS\n" );
516         }
517
518         if (want_bindpw) {
519                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
520                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
521         }
522
523         if ( authmethod == LDAP_AUTH_SASL ) {
524 #ifdef HAVE_CYRUS_SASL
525                 ldap_set_sasl_interact_proc( ld, lutil_sasl_interact );
526
527                 if( sasl_secprops != NULL ) {
528                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
529                                 (void *) sasl_secprops );
530                         
531                         if( rc != LDAP_OPT_SUCCESS ) {
532                                 fprintf( stderr,
533                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
534                                         sasl_secprops );
535                                 return( EXIT_FAILURE );
536                         }
537                 }
538                 
539                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
540                                 sasl_mech, NULL, NULL );
541
542                 if( rc != LDAP_SUCCESS ) {
543                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
544                         return( EXIT_FAILURE );
545                 }
546 #else
547                 fprintf( stderr, "%s was not compiled with SASL support\n",
548                         argv[0] );
549                 return( EXIT_FAILURE );
550 #endif
551         } else {
552                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
553                                 != LDAP_SUCCESS ) {
554                         ldap_perror( ld, "ldap_bind" );
555                         return( EXIT_FAILURE );
556                 }
557         }
558
559         if ( manageDSAit ) {
560                 int err;
561                 LDAPControl c;
562                 LDAPControl *ctrls[2];
563                 ctrls[0] = &c;
564                 ctrls[1] = NULL;
565
566                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
567                 c.ldctl_value.bv_val = NULL;
568                 c.ldctl_value.bv_len = 0;
569                 c.ldctl_iscritical = manageDSAit > 1;
570
571                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
572
573                 if( err != LDAP_OPT_SUCCESS ) {
574                         fprintf( stderr, "Could not set ManageDSAit %scontrol\n",
575                                 c.ldctl_iscritical ? "critical " : "" );
576                         if( c.ldctl_iscritical ) {
577                                 exit( EXIT_FAILURE );
578                         }
579                 }
580         }
581
582         if ( verbose ) {
583                 fprintf( stderr, "filter%s: %s\nrequesting: ",
584                         infile != NULL ? " pattern" : "",
585                         filtpattern );
586
587                 if ( attrs == NULL ) {
588                         fprintf( stderr, "ALL" );
589                 } else {
590                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
591                                 fprintf( stderr, "%s ", attrs[ i ] );
592                         }
593                 }
594                 fprintf( stderr, "\n" );
595         }
596
597         if (ldif < 3 ) {
598                 printf( "version: %d\n\n", ldif ? 1 : 2 );
599         }
600
601         if (ldif < 2 ) {
602                 printf( "#\n# filter%s: %s\n# requesting: ",
603                         infile != NULL ? " pattern" : "",
604                         filtpattern );
605
606                 if ( attrs == NULL ) {
607                         printf( "ALL" );
608                 } else {
609                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
610                                 printf( "%s ", attrs[ i ] );
611                         }
612                 }
613
614                 if ( manageDSAit ) {
615                         printf("\n# with manageDSAit %scontrol",
616                                 manageDSAit > 1 ? "critical " : "" );
617                 }
618
619                 printf( "\n#\n\n" );
620         }
621
622         if ( infile == NULL ) {
623                 rc = dosearch( ld, base, scope, NULL, filtpattern,
624                         attrs, attrsonly, NULL, NULL, NULL, -1 );
625
626         } else {
627                 rc = 0;
628                 first = 1;
629                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
630                         line[ strlen( line ) - 1 ] = '\0';
631                         if ( !first ) {
632                                 putchar( '\n' );
633                         } else {
634                                 first = 0;
635                         }
636                         rc = dosearch( ld, base, scope, filtpattern, line,
637                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
638                 }
639                 if ( fp != stdin ) {
640                         fclose( fp );
641                 }
642         }
643
644         ldap_unbind( ld );
645         return( rc );
646 }
647
648
649 static int dosearch(
650         LDAP    *ld,
651         char    *base,
652         int             scope,
653         char    *filtpatt,
654         char    *value,
655         char    **attrs,
656         int             attrsonly,
657         LDAPControl **sctrls,
658         LDAPControl **cctrls,
659         struct timeval *timelimit,
660         int sizelimit )
661 {
662         char            filter[ BUFSIZ ];
663         int                     rc, first;
664         int                     nresponses;
665         int                     nentries;
666         int                     nreferences;
667         int                     nextended;
668         int                     npartial;
669         LDAPMessage             *res, *msg;
670         ber_int_t       msgid;
671
672         if( filtpatt != NULL ) {
673                 sprintf( filter, filtpatt, value );
674
675                 if ( verbose ) {
676                         fprintf( stderr, "filter is: (%s)\n", filter );
677                 }
678
679                 if( ldif < 2 ) {
680                         printf( "#\n# filter: %s\n#\n", filter );
681                 }
682
683         } else {
684                 sprintf( filter, "%s", value );
685         }
686
687         if ( not ) {
688                 return LDAP_SUCCESS;
689         }
690
691         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
692                 sctrls, cctrls, timelimit, sizelimit, &msgid );
693
694         if( rc != LDAP_SUCCESS ) {
695                 fprintf( stderr, "ldapsearch: ldap_search_ext: %s (%d)\n",
696                         ldap_err2string( rc ), rc );
697                 return( rc );
698         }
699
700         nresponses = nentries = nreferences = nextended = npartial = 0;
701
702         res = NULL;
703
704         while ((rc = ldap_result( ld, LDAP_RES_ANY,
705                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
706                 NULL, &res )) > 0 )
707         {
708                 if( sortattr ) {
709                         (void) ldap_sort_entries( ld, &res,
710                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
711                 }
712
713                 for ( msg = ldap_first_message( ld, res );
714                         msg != NULL;
715                         msg = ldap_next_message( ld, msg ) )
716                 {
717                         if( nresponses++ ) putchar('\n');
718
719                         switch( ldap_msgtype( msg ) ) {
720                         case LDAP_RES_SEARCH_ENTRY:
721                                 nentries++;
722                                 print_entry( ld, msg, attrsonly );
723                                 break;
724
725                         case LDAP_RES_SEARCH_REFERENCE:
726                                 nreferences++;
727                                 print_reference( ld, msg );
728                                 break;
729
730                         case LDAP_RES_EXTENDED:
731                                 nextended++;
732                                 print_extended( ld, msg );
733
734                                 if( ldap_msgid( msg ) == 0 ) {
735                                         /* unsolicited extended operation */
736                                         goto done;
737                                 }
738                                 break;
739
740                         case LDAP_RES_EXTENDED_PARTIAL:
741                                 npartial++;
742                                 print_partial( ld, msg );
743                                 break;
744
745                         case LDAP_RES_SEARCH_RESULT:
746                                 rc = print_result( ld, msg, 1 );
747                                 goto done;
748                         }
749                 }
750
751                 ldap_msgfree( res );
752         }
753
754         if ( rc == -1 ) {
755                 ldap_perror( ld, "ldap_result" );
756                 return( rc );
757         }
758
759 done:
760         if ( ldif < 2 ) {
761                 printf( "\n# numResponses: %d\n", nresponses );
762                 if( nentries ) printf( "# numEntries: %d\n", nentries );
763                 if( nextended ) printf( "# numExtended: %d\n", nextended );
764                 if( npartial ) printf( "# numPartial: %d\n", npartial );
765                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
766         }
767
768         return( rc );
769 }
770
771 static void
772 print_entry(
773         LDAP    *ld,
774         LDAPMessage     *entry,
775         int             attrsonly)
776 {
777         char            *a, *dn, *ufn;
778         char    tmpfname[ 256 ];
779         char    url[ 256 ];
780         int                     i, rc;
781         BerElement              *ber = NULL;
782         struct berval   **bvals;
783         LDAPControl **ctrls = NULL;
784         FILE            *tmpfp;
785
786         dn = ldap_get_dn( ld, entry );
787         ufn = NULL;
788
789         if ( ldif < 2 ) {
790                 ufn = ldap_dn2ufn( dn );
791                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
792         }
793         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
794
795         rc = ldap_get_entry_controls( ld, entry, &ctrls );
796
797         if( rc != LDAP_SUCCESS ) {
798                 fprintf(stderr, "print_entry: %d\n", rc );
799                 ldap_perror( ld, "ldap_get_entry_controls" );
800                 exit( EXIT_FAILURE );
801         }
802
803         if( ctrls ) {
804                 print_ctrls( ctrls );
805                 ldap_controls_free( ctrls );
806         }
807
808         if ( includeufn ) {
809                 if( ufn == NULL ) {
810                         ufn = ldap_dn2ufn( dn );
811                 }
812                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
813         }
814
815         if( ufn != NULL ) ldap_memfree( ufn );
816         ldap_memfree( dn );
817
818         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
819                 a = ldap_next_attribute( ld, entry, ber ) )
820         {
821                 if ( attrsonly ) {
822                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
823
824                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
825                         for ( i = 0; bvals[i] != NULL; i++ ) {
826                                 if ( vals2tmp > 1 || ( vals2tmp
827                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
828                                 {
829                                         int tmpfd;
830                                         /* write value to file */
831                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
832                                                 tmpdir, a );
833                                         tmpfp = NULL;
834
835                                         if ( mktemp( tmpfname ) == NULL ) {
836                                                 perror( tmpfname );
837                                                 continue;
838                                         }
839
840                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
841                                                 perror( tmpfname );
842                                                 continue;
843                                         }
844
845                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
846                                                 perror( tmpfname );
847                                                 continue;
848                                         }
849
850                                         if ( fwrite( bvals[ i ]->bv_val,
851                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
852                                         {
853                                                 perror( tmpfname );
854                                                 fclose( tmpfp );
855                                                 continue;
856                                         }
857
858                                         fclose( tmpfp );
859
860                                         sprintf( url, "%s%s", urlpre,
861                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
862
863                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
864
865                                 } else {
866                                         write_ldif( LDIF_PUT_VALUE, a,
867                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
868                                 }
869                         }
870                         ber_bvecfree( bvals );
871                 }
872         }
873
874         if( ber != NULL ) {
875                 ber_free( ber, 0 );
876         }
877 }
878
879 static void print_reference(
880         LDAP *ld,
881         LDAPMessage *reference )
882 {
883         int rc;
884         char **refs = NULL;
885         LDAPControl **ctrls;
886
887         if( ldif < 2 ) {
888                 printf("# search reference\n");
889         }
890
891         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
892
893         if( rc != LDAP_SUCCESS ) {
894                 ldap_perror(ld, "ldap_parse_reference");
895                 exit( EXIT_FAILURE );
896         }
897
898         if( refs ) {
899                 int i;
900                 for( i=0; refs[i] != NULL; i++ ) {
901                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
902                                 "ref", refs[i], strlen(refs[i]) );
903                 }
904                 ber_memvfree( (void **) refs );
905         }
906
907         if( ctrls ) {
908                 print_ctrls( ctrls );
909                 ldap_controls_free( ctrls );
910         }
911 }
912
913 static void print_extended(
914         LDAP *ld,
915         LDAPMessage *extended )
916 {
917         int rc;
918         char *retoid = NULL;
919         struct berval *retdata = NULL;
920
921         if( ldif < 2 ) {
922                 printf("# extended result response\n");
923         }
924
925         rc = ldap_parse_extended_result( ld, extended,
926                 &retoid, &retdata, 0 );
927
928         if( rc != LDAP_SUCCESS ) {
929                 ldap_perror(ld, "ldap_parse_extended_result");
930                 exit( EXIT_FAILURE );
931         }
932
933         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
934                 "extended", retoid, retoid ? strlen(retoid) : 0 );
935         ber_memfree( retoid );
936
937         if(retdata) {
938                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
939                         "data", retdata->bv_val, retdata->bv_len );
940                 ber_bvfree( retdata );
941         }
942
943         print_result( ld, extended, 0 );
944 }
945
946 static void print_partial(
947         LDAP *ld,
948         LDAPMessage *partial )
949 {
950         int rc;
951         char *retoid = NULL;
952         struct berval *retdata = NULL;
953         LDAPControl **ctrls = NULL;
954
955         if( ldif < 2 ) {
956                 printf("# extended partial response\n");
957         }
958
959         rc = ldap_parse_extended_partial( ld, partial,
960                 &retoid, &retdata, &ctrls, 0 );
961
962         if( rc != LDAP_SUCCESS ) {
963                 ldap_perror(ld, "ldap_parse_extended_partial");
964                 exit( EXIT_FAILURE );
965         }
966
967         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
968                 "partial", retoid, retoid ? strlen(retoid) : 0 );
969
970         ber_memfree( retoid );
971
972         if( retdata ) {
973                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
974                         "data", 
975                         retdata->bv_val, retdata->bv_len );
976
977                 ber_bvfree( retdata );
978         }
979
980         if( ctrls ) {
981                 print_ctrls( ctrls );
982                 ldap_controls_free( ctrls );
983         }
984 }
985
986 static int print_result(
987         LDAP *ld,
988         LDAPMessage *result, int search )
989 {
990         char rst[BUFSIZ];
991         int rc;
992         int err;
993         char *matcheddn = NULL;
994         char *text = NULL;
995         char **refs = NULL;
996         LDAPControl **ctrls = NULL;
997
998         if( search ) {
999                 if ( ldif < 2 ) {
1000                         printf("# search result\n");
1001                 }
1002                 if ( ldif < 1 ) {
1003                         printf("%s: %d\n", "search", ldap_msgid(result) );
1004                 }
1005         }
1006
1007         rc = ldap_parse_result( ld, result,
1008                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1009
1010         if( rc != LDAP_SUCCESS ) {
1011                 ldap_perror(ld, "ldap_parse_result");
1012                 exit( EXIT_FAILURE );
1013         }
1014
1015
1016         if( !ldif ) {
1017                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1018
1019         } else if ( err != LDAP_SUCCESS ) {
1020                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1021         }
1022
1023         if( matcheddn && *matcheddn ) {
1024                 if( !ldif ) {
1025                         write_ldif( LDIF_PUT_VALUE,
1026                                 "matchedDN", matcheddn, strlen(matcheddn) );
1027                 } else {
1028                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1029                 }
1030
1031                 ber_memfree( matcheddn );
1032         }
1033
1034         if( text && *text ) {
1035                 if( !ldif ) {
1036                         write_ldif( LDIF_PUT_TEXT, "text",
1037                                 text, strlen(text) );
1038                 } else {
1039                         fprintf( stderr, "Additional information: %s\n", text );
1040                 }
1041
1042                 ber_memfree( text );
1043         }
1044
1045         if( refs ) {
1046                 int i;
1047                 for( i=0; refs[i] != NULL; i++ ) {
1048                         if( !ldif ) {
1049                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1050                         } else {
1051                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1052                         }
1053                 }
1054
1055                 ber_memvfree( (void **) refs );
1056         }
1057
1058         if( ctrls ) {
1059                 print_ctrls( ctrls );
1060                 ldap_controls_free( ctrls );
1061         }
1062
1063         return err;
1064 }
1065
1066 void print_ctrls( LDAPControl **ctrls ) {
1067         int i;
1068         for(i=0; ctrls[i] != NULL; i++ ) {
1069                 /* control: OID criticality base64value */
1070                 struct berval *b64 = NULL;
1071                 ber_len_t len;
1072                 char *str;
1073                         
1074                 len = strlen( ctrls[i]->ldctl_oid );
1075
1076                 /* add enough for space after OID and the critical value itself */
1077                 len += ctrls[i]->ldctl_iscritical
1078                         ? sizeof("true") : sizeof("false");
1079
1080                 /* convert to base64 */
1081                 if( ctrls[i]->ldctl_value.bv_len ) {
1082                         b64 = ber_memalloc( sizeof(struct berval) );
1083                         
1084                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1085                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1086                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1087
1088                         b64->bv_len = lutil_b64_ntop(
1089                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1090                                 b64->bv_val, b64->bv_len );
1091                 }
1092
1093                 if( b64 ) {
1094                         len += 1 + b64->bv_len;
1095                 }
1096
1097                 str = malloc( len + 1 );
1098                 strcpy( str, ctrls[i]->ldctl_oid );
1099                 strcat( str, ctrls[i]->ldctl_iscritical
1100                         ? " true" : " false" );
1101
1102                 if( b64 ) {
1103                         strcat(str, " ");
1104                         strcat(str, b64->bv_val );
1105                 }
1106
1107                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1108                         "control", str, len );
1109
1110                 free( str );
1111                 ber_bvfree( b64 );
1112         }
1113 }
1114
1115 static int
1116 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1117 {
1118         char    *ldif;
1119
1120         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1121                 return( -1 );
1122         }
1123
1124         fputs( ldif, stdout );
1125         ber_memfree( ldif );
1126
1127         return( 0 );
1128 }