]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
updates from HEAD
[openldap] / clients / tools / ldapsearch.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2002 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 #include "ldap_log.h"
37
38 static char *def_tmpdir;
39 static char *def_urlpre;
40
41 static void
42 usage( const char *s )
43 {
44         fprintf( stderr,
45 "usage: %s [options] [filter [attributes...]]\nwhere:\n"
46 "  filter\tRFC-2254 compliant LDAP search filter\n"
47 "  attributes\twhitespace-separated list of attribute descriptions\n"
48 "    which may include:\n"
49 "      1.1   no attributes\n"
50 "      *     all user attributes\n"
51 "      +     all operational attributes\n"
52
53 "Search options:\n"
54 "  -a deref   one of never (default), always, search, or find\n"
55 "  -A         retrieve attribute names only (no values)\n"
56 "  -b basedn  base dn for search\n"
57 "  -F prefix  URL prefix for files (default: %s)\n"
58 "  -l limit   time limit (in seconds) for search\n"
59 "  -L         print responses in LDIFv1 format\n"
60 "  -LL        print responses in LDIF format without comments\n"
61 "  -LLL       print responses in LDIF format without comments\n"
62 "             and version\n"
63 "  -s scope   one of base, one, or sub (search scope)\n"
64 "  -S attr    sort the results by attribute `attr'\n"
65 "  -t         write binary values to files in temporary directory\n"
66 "  -tt        write all values to files in temporary directory\n"
67 "  -T path    write files to directory specified by path (default: %s)\n"
68 "  -u         include User Friendly entry names in the output\n"
69 "  -z limit   size limit (in entries) for search\n"
70
71 "Common options:\n"
72 "  -d level   set LDAP debugging level to `level'\n"
73 "  -D binddn  bind DN\n"
74 "  -f file    read operations from `file'\n"
75 "  -h host    LDAP server\n"
76 "  -H URI     LDAP Uniform Resource Indentifier(s)\n"
77 "  -I         use SASL Interactive mode\n"
78 "  -k         use Kerberos authentication\n"
79 "  -K         like -k, but do only step 1 of the Kerberos bind\n"
80 "  -M         enable Manage DSA IT control (-MM to make critical)\n"
81 "  -n         show what would be done but don't actually search\n"
82 "  -O props   SASL security properties\n"
83 "  -p port    port on LDAP server\n"
84 "  -P version procotol version (default: 3)\n"
85 "  -Q         use SASL Quiet mode\n"
86 "  -R realm   SASL realm\n"
87 "  -U authcid SASL authentication identity\n"
88 "  -v         run in verbose mode (diagnostics to standard output)\n"
89 "  -w passwd  bind passwd (for simple authentication)\n"
90 "  -W         prompt for bind passwd\n"
91 "  -x         Simple authentication\n"
92 "  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
93 "  -Y mech    SASL mechanism\n"
94 "  -Z         Start TLS request (-ZZ to require successful response)\n"
95 , s, def_urlpre, def_tmpdir );
96
97         exit( EXIT_FAILURE );
98 }
99
100 static void print_entry LDAP_P((
101         LDAP    *ld,
102         LDAPMessage     *entry,
103         int             attrsonly));
104
105 static void print_reference(
106         LDAP *ld,
107         LDAPMessage *reference );
108
109 static void print_extended(
110         LDAP *ld,
111         LDAPMessage *extended );
112
113 static void print_partial(
114         LDAP *ld,
115         LDAPMessage *partial );
116
117 static int print_result(
118         LDAP *ld,
119         LDAPMessage *result,
120         int search );
121
122 static void print_ctrls(
123         LDAPControl **ctrls );
124
125 static int write_ldif LDAP_P((
126         int type,
127         char *name,
128         char *value,
129         ber_len_t vallen ));
130
131 static int dosearch LDAP_P((
132         LDAP    *ld,
133         char    *base,
134         int             scope,
135         char    *filtpatt,
136         char    *value,
137         char    **attrs,
138         int             attrsonly,
139         LDAPControl **sctrls,
140         LDAPControl **cctrls,
141         struct timeval *timeout,
142         int     sizelimit ));
143
144 static char *tmpdir = NULL;
145 static char *urlpre = NULL;
146 static char *prog = NULL;
147 static char     *binddn = NULL;
148 static struct berval passwd = { 0, NULL };
149 static char     *base = NULL;
150 static char     *ldaphost = NULL;
151 static char *ldapuri = NULL;
152 static int      ldapport = 0;
153 #ifdef HAVE_CYRUS_SASL
154 static unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
155 static char     *sasl_realm = NULL;
156 static char     *sasl_authc_id = NULL;
157 static char     *sasl_authz_id = NULL;
158 static char     *sasl_mech = NULL;
159 static char     *sasl_secprops = NULL;
160 #endif
161 static int      use_tls = 0;
162 static char     *sortattr = NULL;
163 static int      verbose, not, includeufn, vals2tmp, ldif;
164
165 static void
166 urlize(char *url)
167 {
168         char *p;
169
170         if (*LDAP_DIRSEP != '/')
171         {
172                 for (p = url; *p; p++)
173                 {
174                         if (*p == *LDAP_DIRSEP)
175                                 *p = '/';
176                 }
177         }
178 }
179
180 int
181 main( int argc, char **argv )
182 {
183         char            *infile, *filtpattern, **attrs = NULL, line[BUFSIZ];
184         FILE            *fp = NULL;
185         int                     rc, i, first, scope, deref, attrsonly, manageDSAit;
186         int                     referrals, timelimit, sizelimit, debug;
187         int             authmethod, version, want_bindpw;
188         LDAP            *ld = NULL;
189         int             valuesReturnFilter;
190         BerElement      *ber;
191         struct berval   *bvalp;
192         char    *vrFilter  = NULL, *control  = NULL, *s;
193
194
195         infile = NULL;
196         debug = verbose = not = vals2tmp = referrals = valuesReturnFilter =
197                 attrsonly = manageDSAit = ldif = want_bindpw = 0;
198
199         lutil_log_initialize(argc, argv);
200
201         deref = sizelimit = timelimit = version = -1;
202
203         scope = LDAP_SCOPE_SUBTREE;
204         authmethod = -1;
205
206         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
207            (def_tmpdir = getenv("TMP")) == NULL &&
208            (def_tmpdir = getenv("TEMP")) == NULL )
209         {
210                 def_tmpdir = LDAP_TMPDIR;
211         }
212
213         if ( !*def_tmpdir )
214                 def_tmpdir = LDAP_TMPDIR;
215
216         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
217
218         if( def_urlpre == NULL ) {
219                 perror( "malloc" );
220                 return EXIT_FAILURE;
221         }
222
223         sprintf( def_urlpre, "file:///%s/",
224                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
225
226         urlize( def_urlpre );
227
228     prog = (prog = strrchr(argv[0], *LDAP_DIRSEP)) == NULL ? argv[0] : prog + 1;
229
230         while (( i = getopt( argc, argv, "Aa:b:E:F:f:Ll:S:s:T:tuz:"
231                 "Cd:D:h:H:IkKMnO:p:P:QR:U:vw:WxX:Y:Z")) != EOF )
232         {
233         switch( i ) {
234         /* Search Options */
235         case 'a':       /* set alias deref option */
236                 if ( strcasecmp( optarg, "never" ) == 0 ) {
237                 deref = LDAP_DEREF_NEVER;
238                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
239                 deref = LDAP_DEREF_SEARCHING;
240                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
241                 deref = LDAP_DEREF_FINDING;
242                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
243                 deref = LDAP_DEREF_ALWAYS;
244                 } else {
245                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
246                 usage(prog);
247                 }
248                 break;
249         case 'A':       /* retrieve attribute names only -- no values */
250                 ++attrsonly;
251                 break;
252         case 'b': /* search base */
253                 base = strdup( optarg );
254                 break;
255         case 'f':       /* input file */
256                 if( infile != NULL ) {
257                         fprintf( stderr, "%s: -f previously specified\n", prog );
258                         return EXIT_FAILURE;
259                 }
260                 infile = strdup( optarg );
261                 break;
262         case 'E': /* controls */
263                 if( version == LDAP_VERSION2 ) {
264                         fprintf( stderr, "%s: -C incompatible with LDAPv%d\n",
265                                 prog, version );
266                         return EXIT_FAILURE;
267                 }
268
269                 /* should be extended to support comma separated list of
270                  *      key/value pairs:  -E foo=123,bar=567
271                  */
272
273                 control = strdup( optarg );
274                 if ( (s = strchr( control, '=' )) == NULL ) {
275                         return EXIT_FAILURE;
276                 }
277
278                 *s++ = '\0';
279                 if ( strcasecmp( control, "mv" ) == 0 ) {
280                         /* ValuesReturnFilter control */
281                         if (valuesReturnFilter!=0) {
282                                 fprintf( stderr, "ValuesReturnFilter previously specified");
283                                 return EXIT_FAILURE;
284                         }
285
286                         if ( *s == '!' ){
287                                 s++;
288                                 valuesReturnFilter=2;
289                         } else {
290                                 valuesReturnFilter=1;
291                         }
292
293                         vrFilter = s;
294                         version = LDAP_VERSION3;
295                         break;
296
297                 } else {
298                         fprintf( stderr, "Invalid control name: %s\n", control );
299                         usage(prog);
300                         return EXIT_FAILURE;
301                 }
302
303         case 'F':       /* uri prefix */
304                 if( urlpre ) free( urlpre );
305                 urlpre = strdup( optarg );
306                 break;
307         case 'l':       /* time limit */
308                 timelimit = atoi( optarg );
309                 if( timelimit < 0 ) {
310                         fprintf( stderr, "%s: invalid timelimit (%d) specified\n",
311                                 prog, timelimit );
312                         return EXIT_FAILURE;
313                 }
314                 break;
315         case 'L':       /* print entries in LDIF format */
316                 ++ldif;
317                 break;
318         case 's':       /* search scope */
319                 if ( strcasecmp( optarg, "base" ) == 0 ) {
320                 scope = LDAP_SCOPE_BASE;
321                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
322                 scope = LDAP_SCOPE_ONELEVEL;
323                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
324                 scope = LDAP_SCOPE_SUBTREE;
325                 } else {
326                 fprintf( stderr, "scope should be base, one, or sub\n" );
327                 usage(prog);
328                 }
329                 break;
330         case 'S':       /* sort attribute */
331                 sortattr = strdup( optarg );
332                 break;
333         case 'u':       /* include UFN */
334                 ++includeufn;
335                 break;
336         case 't':       /* write attribute values to TMPDIR files */
337                 ++vals2tmp;
338                 break;
339         case 'T':       /* tmpdir */
340                 if( tmpdir ) free( tmpdir );
341                 tmpdir = strdup( optarg );
342                 break;
343         case 'z':       /* size limit */
344                 sizelimit = atoi( optarg );
345                 break;
346
347         /* Common Options */
348         case 'C':
349                 referrals++;
350                 break;
351         case 'd':
352             debug |= atoi( optarg );
353             break;
354         case 'D':       /* bind DN */
355                 if( binddn != NULL ) {
356                         fprintf( stderr, "%s: -D previously specified\n", prog );
357                         return EXIT_FAILURE;
358                 }
359             binddn = strdup( optarg );
360             break;
361         case 'h':       /* ldap host */
362                 if( ldapuri != NULL ) {
363                         fprintf( stderr, "%s: -h incompatible with -H\n", prog );
364                         return EXIT_FAILURE;
365                 }
366                 if( ldaphost != NULL ) {
367                         fprintf( stderr, "%s: -h previously specified\n", prog );
368                         return EXIT_FAILURE;
369                 }
370             ldaphost = strdup( optarg );
371             break;
372         case 'H':       /* ldap URI */
373                 if( ldaphost != NULL ) {
374                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
375                         return EXIT_FAILURE;
376                 }
377                 if( ldapport ) {
378                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
379                         return EXIT_FAILURE;
380                 }
381                 if( ldapuri != NULL ) {
382                         fprintf( stderr, "%s: -H previously specified\n", prog );
383                         return EXIT_FAILURE;
384                 }
385             ldapuri = strdup( optarg );
386             break;
387         case 'I':
388 #ifdef HAVE_CYRUS_SASL
389                 if( version == LDAP_VERSION2 ) {
390                         fprintf( stderr, "%s: -I incompatible with version %d\n",
391                                 prog, version );
392                         return EXIT_FAILURE;
393                 }
394                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
395                         fprintf( stderr, "%s: incompatible previous "
396                                 "authentication choice\n",
397                                 prog );
398                         return EXIT_FAILURE;
399                 }
400                 authmethod = LDAP_AUTH_SASL;
401                 version = LDAP_VERSION3;
402                 sasl_flags = LDAP_SASL_INTERACTIVE;
403                 break;
404 #else
405                 fprintf( stderr, "%s: was not compiled with SASL support\n",
406                         prog );
407                 return( EXIT_FAILURE );
408 #endif
409         case 'k':       /* kerberos bind */
410 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
411                 if( version > LDAP_VERSION2 ) {
412                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
413                                 prog, version );
414                         return EXIT_FAILURE;
415                 }
416
417                 if( authmethod != -1 ) {
418                         fprintf( stderr, "%s: -k incompatible with previous "
419                                 "authentication choice\n", prog );
420                         return EXIT_FAILURE;
421                 }
422                         
423                 authmethod = LDAP_AUTH_KRBV4;
424 #else
425                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
426                 return EXIT_FAILURE;
427 #endif
428             break;
429         case 'K':       /* kerberos bind, part one only */
430 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
431                 if( version > LDAP_VERSION2 ) {
432                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
433                                 prog, version );
434                         return EXIT_FAILURE;
435                 }
436                 if( authmethod != -1 ) {
437                         fprintf( stderr, "%s: incompatible with previous "
438                                 "authentication choice\n", prog );
439                         return EXIT_FAILURE;
440                 }
441
442                 authmethod = LDAP_AUTH_KRBV41;
443 #else
444                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
445                 return( EXIT_FAILURE );
446 #endif
447             break;
448         case 'M':
449                 /* enable Manage DSA IT */
450                 if( version == LDAP_VERSION2 ) {
451                         fprintf( stderr, "%s: -M incompatible with LDAPv%d\n",
452                                 prog, version );
453                         return EXIT_FAILURE;
454                 }
455                 manageDSAit++;
456                 version = LDAP_VERSION3;
457                 break;
458         case 'n':       /* print deletes, don't actually do them */
459             ++not;
460             break;
461         case 'O':
462 #ifdef HAVE_CYRUS_SASL
463                 if( sasl_secprops != NULL ) {
464                         fprintf( stderr, "%s: -O previously specified\n", prog );
465                         return EXIT_FAILURE;
466                 }
467                 if( version == LDAP_VERSION2 ) {
468                         fprintf( stderr, "%s: -O incompatible with LDAPv%d\n",
469                                 prog, version );
470                         return EXIT_FAILURE;
471                 }
472                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
473                         fprintf( stderr, "%s: incompatible previous "
474                                 "authentication choice\n", prog );
475                         return EXIT_FAILURE;
476                 }
477                 authmethod = LDAP_AUTH_SASL;
478                 version = LDAP_VERSION3;
479                 sasl_secprops = strdup( optarg );
480 #else
481                 fprintf( stderr, "%s: not compiled with SASL support\n",
482                         prog );
483                 return( EXIT_FAILURE );
484 #endif
485                 break;
486         case 'p':
487                 if( ldapport ) {
488                         fprintf( stderr, "%s: -p previously specified\n", prog );
489                         return EXIT_FAILURE;
490                 }
491             ldapport = atoi( optarg );
492             break;
493         case 'P':
494                 switch( atoi(optarg) ) {
495                 case 2:
496                         if( version == LDAP_VERSION3 ) {
497                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
498                                         prog, version );
499                                 return EXIT_FAILURE;
500                         }
501                         version = LDAP_VERSION2;
502                         break;
503                 case 3:
504                         if( version == LDAP_VERSION2 ) {
505                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
506                                         prog, version );
507                                 return EXIT_FAILURE;
508                         }
509                         version = LDAP_VERSION3;
510                         break;
511                 default:
512                         fprintf( stderr, "%s: protocol version should be 2 or 3\n",
513                                 prog );
514                         usage( prog );
515                         return( EXIT_FAILURE );
516                 } break;
517         case 'Q':
518 #ifdef HAVE_CYRUS_SASL
519                 if( version == LDAP_VERSION2 ) {
520                         fprintf( stderr, "%s: -Q incompatible with version %d\n",
521                                 prog, version );
522                         return EXIT_FAILURE;
523                 }
524                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
525                         fprintf( stderr, "%s: incompatible previous "
526                                 "authentication choice\n",
527                                 prog );
528                         return EXIT_FAILURE;
529                 }
530                 authmethod = LDAP_AUTH_SASL;
531                 version = LDAP_VERSION3;
532                 sasl_flags = LDAP_SASL_QUIET;
533                 break;
534 #else
535                 fprintf( stderr, "%s: not compiled with SASL support\n",
536                         prog );
537                 return( EXIT_FAILURE );
538 #endif
539         case 'R':
540 #ifdef HAVE_CYRUS_SASL
541                 if( sasl_realm != NULL ) {
542                         fprintf( stderr, "%s: -R previously specified\n", prog );
543                         return EXIT_FAILURE;
544                 }
545                 if( version == LDAP_VERSION2 ) {
546                         fprintf( stderr, "%s: -R incompatible with version %d\n",
547                                 prog, version );
548                         return EXIT_FAILURE;
549                 }
550                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
551                         fprintf( stderr, "%s: incompatible previous "
552                                 "authentication choice\n",
553                                 prog );
554                         return EXIT_FAILURE;
555                 }
556                 authmethod = LDAP_AUTH_SASL;
557                 version = LDAP_VERSION3;
558                 sasl_realm = strdup( optarg );
559 #else
560                 fprintf( stderr, "%s: not compiled with SASL support\n",
561                         prog );
562                 return( EXIT_FAILURE );
563 #endif
564                 break;
565         case 'U':
566 #ifdef HAVE_CYRUS_SASL
567                 if( sasl_authc_id != NULL ) {
568                         fprintf( stderr, "%s: -U previously specified\n", prog );
569                         return EXIT_FAILURE;
570                 }
571                 if( version == LDAP_VERSION2 ) {
572                         fprintf( stderr, "%s: -U incompatible with version %d\n",
573                                 prog, version );
574                         return EXIT_FAILURE;
575                 }
576                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
577                         fprintf( stderr, "%s: incompatible previous "
578                                 "authentication choice\n",
579                                 prog );
580                         return EXIT_FAILURE;
581                 }
582                 authmethod = LDAP_AUTH_SASL;
583                 version = LDAP_VERSION3;
584                 sasl_authc_id = strdup( optarg );
585 #else
586                 fprintf( stderr, "%s: not compiled with SASL support\n",
587                         prog );
588                 return( EXIT_FAILURE );
589 #endif
590                 break;
591         case 'v':       /* verbose mode */
592             verbose++;
593             break;
594         case 'w':       /* password */
595             passwd.bv_val = strdup( optarg );
596                 {
597                         char* p;
598
599                         for( p = optarg; *p != '\0'; p++ ) {
600                                 *p = '\0';
601                         }
602                 }
603                 passwd.bv_len = strlen( passwd.bv_val );
604             break;
605         case 'W':
606                 want_bindpw++;
607                 break;
608         case 'Y':
609 #ifdef HAVE_CYRUS_SASL
610                 if( sasl_mech != NULL ) {
611                         fprintf( stderr, "%s: -Y previously specified\n", prog );
612                         return EXIT_FAILURE;
613                 }
614                 if( version == LDAP_VERSION2 ) {
615                         fprintf( stderr, "%s: -Y incompatible with version %d\n",
616                                 prog, version );
617                         return EXIT_FAILURE;
618                 }
619                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
620                         fprintf( stderr, "%s: incompatible with authentication choice\n", prog );
621                         return EXIT_FAILURE;
622                 }
623                 authmethod = LDAP_AUTH_SASL;
624                 version = LDAP_VERSION3;
625                 sasl_mech = strdup( optarg );
626 #else
627                 fprintf( stderr, "%s: not compiled with SASL support\n",
628                         prog );
629                 return( EXIT_FAILURE );
630 #endif
631                 break;
632         case 'x':
633                 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
634                         fprintf( stderr, "%s: incompatible with previous "
635                                 "authentication choice\n", prog );
636                         return EXIT_FAILURE;
637                 }
638                 authmethod = LDAP_AUTH_SIMPLE;
639                 break;
640         case 'X':
641 #ifdef HAVE_CYRUS_SASL
642                 if( sasl_authz_id != NULL ) {
643                         fprintf( stderr, "%s: -X previously specified\n", prog );
644                         return EXIT_FAILURE;
645                 }
646                 if( version == LDAP_VERSION2 ) {
647                         fprintf( stderr, "%s: -X incompatible with LDAPv%d\n",
648                                 prog, version );
649                         return EXIT_FAILURE;
650                 }
651                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
652                         fprintf( stderr, "%s: -X incompatible with "
653                                 "authentication choice\n", prog );
654                         return EXIT_FAILURE;
655                 }
656                 authmethod = LDAP_AUTH_SASL;
657                 version = LDAP_VERSION3;
658                 sasl_authz_id = strdup( optarg );
659 #else
660                 fprintf( stderr, "%s: not compiled with SASL support\n",
661                         prog );
662                 return( EXIT_FAILURE );
663 #endif
664                 break;
665         case 'Z':
666 #ifdef HAVE_TLS
667                 if( version == LDAP_VERSION2 ) {
668                         fprintf( stderr, "%s: -Z incompatible with version %d\n",
669                                 prog, version );
670                         return EXIT_FAILURE;
671                 }
672                 version = LDAP_VERSION3;
673                 use_tls++;
674 #else
675                 fprintf( stderr, "%s: not compiled with TLS support\n",
676                         prog );
677                 return( EXIT_FAILURE );
678 #endif
679                 break;
680         default:
681                 fprintf( stderr, "%s: unrecognized option -%c\n",
682                         prog, optopt );
683                 usage(prog);
684         }
685         }
686
687         if (version == -1) {
688                 version = LDAP_VERSION3;
689         }
690         if (authmethod == -1 && version > LDAP_VERSION2) {
691 #ifdef HAVE_CYRUS_SASL
692                 authmethod = LDAP_AUTH_SASL;
693 #else
694                 authmethod = LDAP_AUTH_SIMPLE;
695 #endif
696         }
697
698         if (( argc - optind < 1 ) ||
699                 ( *argv[optind] != '(' /*')'*/ &&
700                 ( strchr( argv[optind], '=' ) == NULL ) ) )
701         {
702                 filtpattern = "(objectclass=*)";
703         } else {
704                 filtpattern = strdup( argv[optind++] );
705         }
706
707         if ( argv[optind] != NULL ) {
708                 attrs = &argv[optind];
709         }
710
711         if ( infile != NULL ) {
712                 if ( infile[0] == '-' && infile[1] == '\0' ) {
713                         fp = stdin;
714                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
715                         perror( infile );
716                         return EXIT_FAILURE;
717                 }
718         }
719
720         if ( tmpdir == NULL ) {
721                 tmpdir = def_tmpdir;
722
723                 if ( urlpre == NULL )
724                         urlpre = def_urlpre;
725         }
726
727         if( urlpre == NULL ) {
728                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
729
730                 if( urlpre == NULL ) {
731                         perror( "malloc" );
732                         return EXIT_FAILURE;
733                 }
734
735                 sprintf( urlpre, "file:///%s/",
736                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
737
738                 urlize( urlpre );
739         }
740
741         if ( debug ) {
742                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
743                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
744                 }
745                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
746                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
747                 }
748                 ldif_debug = debug;
749         }
750
751 #ifdef SIGPIPE
752         (void) SIGNAL( SIGPIPE, SIG_IGN );
753 #endif
754
755         if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
756                 if ( verbose ) {
757                         fprintf( stderr, "ldap_init( %s, %d )\n",
758                                 ldaphost != NULL ? ldaphost : "<DEFAULT>",
759                                 ldapport );
760                 }
761
762                 ld = ldap_init( ldaphost, ldapport );
763                 if( ld == NULL ) {
764                         perror("ldapsearch: ldap_init");
765                         return EXIT_FAILURE;
766                 }
767
768         } else {
769                 if ( verbose ) {
770                         fprintf( stderr, "ldap_initialize( %s )\n",
771                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
772                 }
773
774                 rc = ldap_initialize( &ld, ldapuri );
775                 if( rc != LDAP_SUCCESS ) {
776                         fprintf( stderr, "Could not create LDAP session handle (%d): %s\n",
777                                 rc, ldap_err2string(rc) );
778                         return EXIT_FAILURE;
779                 }
780         }
781
782         if (deref != -1 &&
783                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
784         {
785                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
786                 return EXIT_FAILURE;
787         }
788         if (timelimit != -1 &&
789                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
790         {
791                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
792                 return EXIT_FAILURE;
793         }
794         if (sizelimit != -1 &&
795                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
796         {
797                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
798                 return EXIT_FAILURE;
799         }
800
801         /* referrals */
802         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
803                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
804         {
805                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
806                         referrals ? "on" : "off" );
807                 return EXIT_FAILURE;
808         }
809
810         if (version == -1 ) {
811                 version = LDAP_VERSION3;
812         }
813
814         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
815                 != LDAP_OPT_SUCCESS )
816         {
817                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
818                         version );
819                 return EXIT_FAILURE;
820         }
821
822         if ( use_tls && ( ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS )) {
823                 ldap_perror( ld, "ldap_start_tls" );
824                 if ( use_tls > 1 ) {
825                         return EXIT_FAILURE;
826                 }
827         }
828
829         if (want_bindpw) {
830                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
831                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
832         }
833
834         if ( authmethod == LDAP_AUTH_SASL ) {
835 #ifdef HAVE_CYRUS_SASL
836                 void *defaults;
837
838                 if( sasl_secprops != NULL ) {
839                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
840                                 (void *) sasl_secprops );
841                         
842                         if( rc != LDAP_OPT_SUCCESS ) {
843                                 fprintf( stderr,
844                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
845                                         sasl_secprops );
846                                 return( EXIT_FAILURE );
847                         }
848                 }
849                 
850                 defaults = lutil_sasl_defaults( ld,
851                         sasl_mech,
852                         sasl_realm,
853                         sasl_authc_id,
854                         passwd.bv_val,
855                         sasl_authz_id );
856
857                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
858                         sasl_mech, NULL, NULL,
859                         sasl_flags, lutil_sasl_interact, defaults );
860
861                 if( rc != LDAP_SUCCESS ) {
862                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
863                         return( EXIT_FAILURE );
864                 }
865 #else
866                 fprintf( stderr, "%s: not compiled with SASL support\n",
867                         prog);
868                 return( EXIT_FAILURE );
869 #endif
870         } else {
871                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
872                                 != LDAP_SUCCESS ) {
873                         ldap_perror( ld, "ldap_bind" );
874                         return( EXIT_FAILURE );
875                 }
876         }
877
878         if ( manageDSAit || valuesReturnFilter ) {
879                 int err;
880                 int i=0;
881                 LDAPControl c1,c2;
882                 LDAPControl *ctrls[3];
883                 
884                 if ( manageDSAit ) {
885                         ctrls[i++]=&c1;
886                         ctrls[i] = NULL;
887
888                         c1.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
889                         c1.ldctl_value.bv_val = NULL;
890                         c1.ldctl_value.bv_len = 0;
891                         c1.ldctl_iscritical = manageDSAit > 1;
892                 }
893
894                 if ( valuesReturnFilter ) {
895                         struct berval *bvalp;
896                         ctrls[i++]=&c2;
897                         ctrls[i] = NULL;
898
899                         c2.ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
900                         c2.ldctl_iscritical = valuesReturnFilter > 1;
901                     
902                         if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) 
903                                 exit( EXIT_FAILURE );
904
905                         if ( err = put_vrFilter(ber, vrFilter)==-1 ) {
906                                 ber_free( ber, 1 );
907                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
908                                 exit( EXIT_FAILURE );
909                         }
910
911                         if ( ber_flatten( ber, &bvalp ) == LBER_ERROR ) 
912                                 return LDAP_NO_MEMORY;
913
914                         c2.ldctl_value=(*bvalp);
915
916                 }
917         
918                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
919
920                 ber_bvfree(bvalp);
921                 ber_free( ber, 1 );
922
923                 if( err != LDAP_OPT_SUCCESS ) {
924                         fprintf( stderr, "Could not set %scontrols\n",
925                                 (c1.ldctl_iscritical || c2.ldctl_iscritical)
926                                 ? "critical " : "" );
927                         if( c1.ldctl_iscritical && c2.ldctl_iscritical ) {
928                                 exit( EXIT_FAILURE );
929                         }
930                 }
931         }
932
933         if ( verbose ) {
934                 fprintf( stderr, "filter%s: %s\nrequesting: ",
935                         infile != NULL ? " pattern" : "",
936                         filtpattern );
937
938                 if ( attrs == NULL ) {
939                         fprintf( stderr, "ALL" );
940                 } else {
941                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
942                                 fprintf( stderr, "%s ", attrs[ i ] );
943                         }
944                 }
945                 fprintf( stderr, "\n" );
946         }
947
948         if ( ldif == 0 ) {
949                 printf( "# extended LDIF\n" );
950         } else if ( ldif < 3 ) {
951                 printf( "version: %d\n\n", 1 );
952         }
953
954         if (ldif < 2 ) {
955                 printf( "#\n# LDAPv%d\n# filter%s: %s\n# requesting: ",
956                         version,
957                         infile != NULL ? " pattern" : "",
958                         filtpattern );
959
960                 if ( attrs == NULL ) {
961                         printf( "ALL" );
962                 } else {
963                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
964                                 printf( "%s ", attrs[ i ] );
965                         }
966                 }
967
968                 if ( manageDSAit ) {
969                         printf("\n# with manageDSAit %scontrol",
970                                 manageDSAit > 1 ? "critical " : "" );
971                 }
972
973                 printf( "\n#\n\n" );
974         }
975
976         if ( infile == NULL ) {
977                 rc = dosearch( ld, base, scope, NULL, filtpattern,
978                         attrs, attrsonly, NULL, NULL, NULL, -1 );
979
980         } else {
981                 rc = 0;
982                 first = 1;
983                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
984                         line[ strlen( line ) - 1 ] = '\0';
985                         if ( !first ) {
986                                 putchar( '\n' );
987                         } else {
988                                 first = 0;
989                         }
990                         rc = dosearch( ld, base, scope, filtpattern, line,
991                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
992                 }
993                 if ( fp != stdin ) {
994                         fclose( fp );
995                 }
996         }
997
998         ldap_unbind( ld );
999         return( rc );
1000 }
1001
1002
1003 static int dosearch(
1004         LDAP    *ld,
1005         char    *base,
1006         int             scope,
1007         char    *filtpatt,
1008         char    *value,
1009         char    **attrs,
1010         int             attrsonly,
1011         LDAPControl **sctrls,
1012         LDAPControl **cctrls,
1013         struct timeval *timeout,
1014         int sizelimit )
1015 {
1016         char                    *filter;
1017         int                     rc;
1018         int                     nresponses;
1019         int                     nentries;
1020         int                     nreferences;
1021         int                     nextended;
1022         int                     npartial;
1023         LDAPMessage             *res, *msg;
1024         ber_int_t       msgid;
1025
1026         if( filtpatt != NULL ) {
1027                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1028                 if( filter == NULL ) {
1029                         perror( "malloc" );
1030                         return EXIT_FAILURE;
1031                 }
1032
1033                 sprintf( filter, filtpatt, value );
1034
1035                 if ( verbose ) {
1036                         fprintf( stderr, "filter: %s\n", filter );
1037                 }
1038
1039                 if( ldif < 2 ) {
1040                         printf( "#\n# filter: %s\n#\n", filter );
1041                 }
1042
1043         } else {
1044                 filter = value;
1045         }
1046
1047         if ( not ) {
1048                 return LDAP_SUCCESS;
1049         }
1050
1051         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1052                 sctrls, cctrls, timeout, sizelimit, &msgid );
1053
1054         if ( filtpatt != NULL ) {
1055                 free( filter );
1056         }
1057
1058         if( rc != LDAP_SUCCESS ) {
1059                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1060                         prog, ldap_err2string( rc ), rc );
1061                 return( rc );
1062         }
1063
1064         nresponses = nentries = nreferences = nextended = npartial = 0;
1065
1066         res = NULL;
1067
1068         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1069                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1070                 NULL, &res )) > 0 )
1071         {
1072                 if( sortattr ) {
1073                         (void) ldap_sort_entries( ld, &res,
1074                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1075                 }
1076
1077                 for ( msg = ldap_first_message( ld, res );
1078                         msg != NULL;
1079                         msg = ldap_next_message( ld, msg ) )
1080                 {
1081                         if( nresponses++ ) putchar('\n');
1082
1083                         switch( ldap_msgtype( msg ) ) {
1084                         case LDAP_RES_SEARCH_ENTRY:
1085                                 nentries++;
1086                                 print_entry( ld, msg, attrsonly );
1087                                 break;
1088
1089                         case LDAP_RES_SEARCH_REFERENCE:
1090                                 nreferences++;
1091                                 print_reference( ld, msg );
1092                                 break;
1093
1094                         case LDAP_RES_EXTENDED:
1095                                 nextended++;
1096                                 print_extended( ld, msg );
1097
1098                                 if( ldap_msgid( msg ) == 0 ) {
1099                                         /* unsolicited extended operation */
1100                                         goto done;
1101                                 }
1102                                 break;
1103
1104                         case LDAP_RES_EXTENDED_PARTIAL:
1105                                 npartial++;
1106                                 print_partial( ld, msg );
1107                                 break;
1108
1109                         case LDAP_RES_SEARCH_RESULT:
1110                                 rc = print_result( ld, msg, 1 );
1111                                 goto done;
1112                         }
1113                 }
1114
1115                 ldap_msgfree( res );
1116         }
1117
1118         if ( rc == -1 ) {
1119                 ldap_perror( ld, "ldap_result" );
1120                 return( rc );
1121         }
1122
1123 done:
1124         if ( ldif < 2 ) {
1125                 printf( "\n# numResponses: %d\n", nresponses );
1126                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1127                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1128                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1129                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1130         }
1131
1132         return( rc );
1133 }
1134
1135 static void
1136 print_entry(
1137         LDAP    *ld,
1138         LDAPMessage     *entry,
1139         int             attrsonly)
1140 {
1141         char            *a, *dn, *ufn;
1142         char    tmpfname[ 256 ];
1143         char    url[ 256 ];
1144         int                     i, rc;
1145         BerElement              *ber = NULL;
1146         struct berval   **bvals;
1147         LDAPControl **ctrls = NULL;
1148         FILE            *tmpfp;
1149
1150         dn = ldap_get_dn( ld, entry );
1151         ufn = NULL;
1152
1153         if ( ldif < 2 ) {
1154                 ufn = ldap_dn2ufn( dn );
1155                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1156         }
1157         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1158
1159         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1160
1161         if( rc != LDAP_SUCCESS ) {
1162                 fprintf(stderr, "print_entry: %d\n", rc );
1163                 ldap_perror( ld, "ldap_get_entry_controls" );
1164                 exit( EXIT_FAILURE );
1165         }
1166
1167         if( ctrls ) {
1168                 print_ctrls( ctrls );
1169                 ldap_controls_free( ctrls );
1170         }
1171
1172         if ( includeufn ) {
1173                 if( ufn == NULL ) {
1174                         ufn = ldap_dn2ufn( dn );
1175                 }
1176                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1177         }
1178
1179         if( ufn != NULL ) ldap_memfree( ufn );
1180         ldap_memfree( dn );
1181
1182         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1183                 a = ldap_next_attribute( ld, entry, ber ) )
1184         {
1185                 if ( attrsonly ) {
1186                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1187
1188                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1189                         for ( i = 0; bvals[i] != NULL; i++ ) {
1190                                 if ( vals2tmp > 1 || ( vals2tmp
1191                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1192                                 {
1193                                         int tmpfd;
1194                                         /* write value to file */
1195                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1196                                                 tmpdir, a );
1197                                         tmpfp = NULL;
1198
1199                                         tmpfd = mkstemp( tmpfname );
1200
1201                                         if ( tmpfd < 0  ) {
1202                                                 perror( tmpfname );
1203                                                 continue;
1204                                         }
1205
1206                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1207                                                 perror( tmpfname );
1208                                                 continue;
1209                                         }
1210
1211                                         if ( fwrite( bvals[ i ]->bv_val,
1212                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1213                                         {
1214                                                 perror( tmpfname );
1215                                                 fclose( tmpfp );
1216                                                 continue;
1217                                         }
1218
1219                                         fclose( tmpfp );
1220
1221                                         sprintf( url, "%s%s", urlpre,
1222                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1223
1224                                         urlize( url );
1225                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1226
1227                                 } else {
1228                                         write_ldif( LDIF_PUT_VALUE, a,
1229                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1230                                 }
1231                         }
1232                         ber_bvecfree( bvals );
1233                 }
1234         }
1235
1236         if( ber != NULL ) {
1237                 ber_free( ber, 0 );
1238         }
1239 }
1240
1241 static void print_reference(
1242         LDAP *ld,
1243         LDAPMessage *reference )
1244 {
1245         int rc;
1246         char **refs = NULL;
1247         LDAPControl **ctrls;
1248
1249         if( ldif < 2 ) {
1250                 printf("# search reference\n");
1251         }
1252
1253         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1254
1255         if( rc != LDAP_SUCCESS ) {
1256                 ldap_perror(ld, "ldap_parse_reference");
1257                 exit( EXIT_FAILURE );
1258         }
1259
1260         if( refs ) {
1261                 int i;
1262                 for( i=0; refs[i] != NULL; i++ ) {
1263                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1264                                 "ref", refs[i], strlen(refs[i]) );
1265                 }
1266                 ber_memvfree( (void **) refs );
1267         }
1268
1269         if( ctrls ) {
1270                 print_ctrls( ctrls );
1271                 ldap_controls_free( ctrls );
1272         }
1273 }
1274
1275 static void print_extended(
1276         LDAP *ld,
1277         LDAPMessage *extended )
1278 {
1279         int rc;
1280         char *retoid = NULL;
1281         struct berval *retdata = NULL;
1282
1283         if( ldif < 2 ) {
1284                 printf("# extended result response\n");
1285         }
1286
1287         rc = ldap_parse_extended_result( ld, extended,
1288                 &retoid, &retdata, 0 );
1289
1290         if( rc != LDAP_SUCCESS ) {
1291                 ldap_perror(ld, "ldap_parse_extended_result");
1292                 exit( EXIT_FAILURE );
1293         }
1294
1295         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1296                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1297         ber_memfree( retoid );
1298
1299         if(retdata) {
1300                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1301                         "data", retdata->bv_val, retdata->bv_len );
1302                 ber_bvfree( retdata );
1303         }
1304
1305         print_result( ld, extended, 0 );
1306 }
1307
1308 static void print_partial(
1309         LDAP *ld,
1310         LDAPMessage *partial )
1311 {
1312         int rc;
1313         char *retoid = NULL;
1314         struct berval *retdata = NULL;
1315         LDAPControl **ctrls = NULL;
1316
1317         if( ldif < 2 ) {
1318                 printf("# extended partial response\n");
1319         }
1320
1321         rc = ldap_parse_extended_partial( ld, partial,
1322                 &retoid, &retdata, &ctrls, 0 );
1323
1324         if( rc != LDAP_SUCCESS ) {
1325                 ldap_perror(ld, "ldap_parse_extended_partial");
1326                 exit( EXIT_FAILURE );
1327         }
1328
1329         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1330                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1331
1332         ber_memfree( retoid );
1333
1334         if( retdata ) {
1335                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1336                         "data", 
1337                         retdata->bv_val, retdata->bv_len );
1338
1339                 ber_bvfree( retdata );
1340         }
1341
1342         if( ctrls ) {
1343                 print_ctrls( ctrls );
1344                 ldap_controls_free( ctrls );
1345         }
1346 }
1347
1348 static int print_result(
1349         LDAP *ld,
1350         LDAPMessage *result, int search )
1351 {
1352         int rc;
1353         int err;
1354         char *matcheddn = NULL;
1355         char *text = NULL;
1356         char **refs = NULL;
1357         LDAPControl **ctrls = NULL;
1358
1359         if( search ) {
1360                 if ( ldif < 2 ) {
1361                         printf("# search result\n");
1362                 }
1363                 if ( ldif < 1 ) {
1364                         printf("%s: %d\n", "search", ldap_msgid(result) );
1365                 }
1366         }
1367
1368         rc = ldap_parse_result( ld, result,
1369                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1370
1371         if( rc != LDAP_SUCCESS ) {
1372                 ldap_perror(ld, "ldap_parse_result");
1373                 exit( EXIT_FAILURE );
1374         }
1375
1376
1377         if( !ldif ) {
1378                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1379
1380         } else if ( err != LDAP_SUCCESS ) {
1381                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1382         }
1383
1384         if( matcheddn && *matcheddn ) {
1385                 if( !ldif ) {
1386                         write_ldif( LDIF_PUT_VALUE,
1387                                 "matchedDN", matcheddn, strlen(matcheddn) );
1388                 } else {
1389                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1390                 }
1391
1392                 ber_memfree( matcheddn );
1393         }
1394
1395         if( text && *text ) {
1396                 if( !ldif ) {
1397                         write_ldif( LDIF_PUT_TEXT, "text",
1398                                 text, strlen(text) );
1399                 } else {
1400                         fprintf( stderr, "Additional information: %s\n", text );
1401                 }
1402
1403                 ber_memfree( text );
1404         }
1405
1406         if( refs ) {
1407                 int i;
1408                 for( i=0; refs[i] != NULL; i++ ) {
1409                         if( !ldif ) {
1410                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1411                         } else {
1412                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1413                         }
1414                 }
1415
1416                 ber_memvfree( (void **) refs );
1417         }
1418
1419         if( ctrls ) {
1420                 print_ctrls( ctrls );
1421                 ldap_controls_free( ctrls );
1422         }
1423
1424         return err;
1425 }
1426
1427 static void print_ctrls(
1428         LDAPControl **ctrls )
1429 {
1430         int i;
1431         for(i=0; ctrls[i] != NULL; i++ ) {
1432                 /* control: OID criticality base64value */
1433                 struct berval *b64 = NULL;
1434                 ber_len_t len;
1435                 char *str;
1436                         
1437                 len = strlen( ctrls[i]->ldctl_oid );
1438
1439                 /* add enough for space after OID and the critical value itself */
1440                 len += ctrls[i]->ldctl_iscritical
1441                         ? sizeof("true") : sizeof("false");
1442
1443                 /* convert to base64 */
1444                 if( ctrls[i]->ldctl_value.bv_len ) {
1445                         b64 = ber_memalloc( sizeof(struct berval) );
1446                         
1447                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1448                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1449                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1450
1451                         b64->bv_len = lutil_b64_ntop(
1452                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1453                                 b64->bv_val, b64->bv_len );
1454                 }
1455
1456                 if( b64 ) {
1457                         len += 1 + b64->bv_len;
1458                 }
1459
1460                 str = malloc( len + 1 );
1461                 strcpy( str, ctrls[i]->ldctl_oid );
1462                 strcat( str, ctrls[i]->ldctl_iscritical
1463                         ? " true" : " false" );
1464
1465                 if( b64 ) {
1466                         strcat(str, " ");
1467                         strcat(str, b64->bv_val );
1468                 }
1469
1470                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1471                         "control", str, len );
1472
1473                 free( str );
1474                 ber_bvfree( b64 );
1475         }
1476 }
1477
1478 static int
1479 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1480 {
1481         char    *ldif;
1482
1483         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1484                 return( -1 );
1485         }
1486
1487         fputs( ldif, stdout );
1488         ber_memfree( ldif );
1489
1490         return( 0 );
1491 }