]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
VLV clean
[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                                 return EXIT_FAILURE;
904                         }
905
906                 if ( err = ldap_put_vrFilter(ber, vrFilter)==-1 ) {
907                                 ber_free( ber, 1 );
908                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
909                                 return EXIT_FAILURE;
910                         }
911
912                         if ( ber_flatten( ber, &bvalp ) == LBER_ERROR ) {
913                                 return EXIT_FAILURE;
914                         }
915
916                         c2.ldctl_value=(*bvalp);
917                 }
918         
919                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
920
921                 ber_bvfree(bvalp);
922                 ber_free( ber, 1 );
923
924                 if( err != LDAP_OPT_SUCCESS ) {
925                         fprintf( stderr, "Could not set %scontrols\n",
926                                 (c1.ldctl_iscritical || c2.ldctl_iscritical)
927                                 ? "critical " : "" );
928                         if( c1.ldctl_iscritical && c2.ldctl_iscritical ) {
929                                 return EXIT_FAILURE;
930                         }
931                 }
932         }
933
934         if ( verbose ) {
935                 fprintf( stderr, "filter%s: %s\nrequesting: ",
936                         infile != NULL ? " pattern" : "",
937                         filtpattern );
938
939                 if ( attrs == NULL ) {
940                         fprintf( stderr, "ALL" );
941                 } else {
942                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
943                                 fprintf( stderr, "%s ", attrs[ i ] );
944                         }
945                 }
946                 fprintf( stderr, "\n" );
947         }
948
949         if ( ldif == 0 ) {
950                 printf( "# extended LDIF\n" );
951         } else if ( ldif < 3 ) {
952                 printf( "version: %d\n\n", 1 );
953         }
954
955         if (ldif < 2 ) {
956                 printf( "#\n# LDAPv%d\n# filter%s: %s\n# requesting: ",
957                         version,
958                         infile != NULL ? " pattern" : "",
959                         filtpattern );
960
961                 if ( attrs == NULL ) {
962                         printf( "ALL" );
963                 } else {
964                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
965                                 printf( "%s ", attrs[ i ] );
966                         }
967                 }
968
969                 if ( manageDSAit ) {
970                         printf("\n# with manageDSAit %scontrol",
971                                 manageDSAit > 1 ? "critical " : "" );
972                 }
973
974                 printf( "\n#\n\n" );
975         }
976
977         if ( infile == NULL ) {
978                 rc = dosearch( ld, base, scope, NULL, filtpattern,
979                         attrs, attrsonly, NULL, NULL, NULL, -1 );
980
981         } else {
982                 rc = 0;
983                 first = 1;
984                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
985                         line[ strlen( line ) - 1 ] = '\0';
986                         if ( !first ) {
987                                 putchar( '\n' );
988                         } else {
989                                 first = 0;
990                         }
991                         rc = dosearch( ld, base, scope, filtpattern, line,
992                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
993                 }
994                 if ( fp != stdin ) {
995                         fclose( fp );
996                 }
997         }
998
999         ldap_unbind( ld );
1000         return( rc );
1001 }
1002
1003
1004 static int dosearch(
1005         LDAP    *ld,
1006         char    *base,
1007         int             scope,
1008         char    *filtpatt,
1009         char    *value,
1010         char    **attrs,
1011         int             attrsonly,
1012         LDAPControl **sctrls,
1013         LDAPControl **cctrls,
1014         struct timeval *timeout,
1015         int sizelimit )
1016 {
1017         char                    *filter;
1018         int                     rc;
1019         int                     nresponses;
1020         int                     nentries;
1021         int                     nreferences;
1022         int                     nextended;
1023         int                     npartial;
1024         LDAPMessage             *res, *msg;
1025         ber_int_t       msgid;
1026
1027         if( filtpatt != NULL ) {
1028                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1029                 if( filter == NULL ) {
1030                         perror( "malloc" );
1031                         return EXIT_FAILURE;
1032                 }
1033
1034                 sprintf( filter, filtpatt, value );
1035
1036                 if ( verbose ) {
1037                         fprintf( stderr, "filter: %s\n", filter );
1038                 }
1039
1040                 if( ldif < 2 ) {
1041                         printf( "#\n# filter: %s\n#\n", filter );
1042                 }
1043
1044         } else {
1045                 filter = value;
1046         }
1047
1048         if ( not ) {
1049                 return LDAP_SUCCESS;
1050         }
1051
1052         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1053                 sctrls, cctrls, timeout, sizelimit, &msgid );
1054
1055         if ( filtpatt != NULL ) {
1056                 free( filter );
1057         }
1058
1059         if( rc != LDAP_SUCCESS ) {
1060                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1061                         prog, ldap_err2string( rc ), rc );
1062                 return( rc );
1063         }
1064
1065         nresponses = nentries = nreferences = nextended = npartial = 0;
1066
1067         res = NULL;
1068
1069         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1070                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1071                 NULL, &res )) > 0 )
1072         {
1073                 if( sortattr ) {
1074                         (void) ldap_sort_entries( ld, &res,
1075                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1076                 }
1077
1078                 for ( msg = ldap_first_message( ld, res );
1079                         msg != NULL;
1080                         msg = ldap_next_message( ld, msg ) )
1081                 {
1082                         if( nresponses++ ) putchar('\n');
1083
1084                         switch( ldap_msgtype( msg ) ) {
1085                         case LDAP_RES_SEARCH_ENTRY:
1086                                 nentries++;
1087                                 print_entry( ld, msg, attrsonly );
1088                                 break;
1089
1090                         case LDAP_RES_SEARCH_REFERENCE:
1091                                 nreferences++;
1092                                 print_reference( ld, msg );
1093                                 break;
1094
1095                         case LDAP_RES_EXTENDED:
1096                                 nextended++;
1097                                 print_extended( ld, msg );
1098
1099                                 if( ldap_msgid( msg ) == 0 ) {
1100                                         /* unsolicited extended operation */
1101                                         goto done;
1102                                 }
1103                                 break;
1104
1105                         case LDAP_RES_EXTENDED_PARTIAL:
1106                                 npartial++;
1107                                 print_partial( ld, msg );
1108                                 break;
1109
1110                         case LDAP_RES_SEARCH_RESULT:
1111                                 rc = print_result( ld, msg, 1 );
1112                                 goto done;
1113                         }
1114                 }
1115
1116                 ldap_msgfree( res );
1117         }
1118
1119         if ( rc == -1 ) {
1120                 ldap_perror( ld, "ldap_result" );
1121                 return( rc );
1122         }
1123
1124 done:
1125         if ( ldif < 2 ) {
1126                 printf( "\n# numResponses: %d\n", nresponses );
1127                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1128                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1129                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1130                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1131         }
1132
1133         return( rc );
1134 }
1135
1136 static void
1137 print_entry(
1138         LDAP    *ld,
1139         LDAPMessage     *entry,
1140         int             attrsonly)
1141 {
1142         char            *a, *dn, *ufn;
1143         char    tmpfname[ 256 ];
1144         char    url[ 256 ];
1145         int                     i, rc;
1146         BerElement              *ber = NULL;
1147         struct berval   **bvals;
1148         LDAPControl **ctrls = NULL;
1149         FILE            *tmpfp;
1150
1151         dn = ldap_get_dn( ld, entry );
1152         ufn = NULL;
1153
1154         if ( ldif < 2 ) {
1155                 ufn = ldap_dn2ufn( dn );
1156                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1157         }
1158         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1159
1160         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1161
1162         if( rc != LDAP_SUCCESS ) {
1163                 fprintf(stderr, "print_entry: %d\n", rc );
1164                 ldap_perror( ld, "ldap_get_entry_controls" );
1165                 exit( EXIT_FAILURE );
1166         }
1167
1168         if( ctrls ) {
1169                 print_ctrls( ctrls );
1170                 ldap_controls_free( ctrls );
1171         }
1172
1173         if ( includeufn ) {
1174                 if( ufn == NULL ) {
1175                         ufn = ldap_dn2ufn( dn );
1176                 }
1177                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1178         }
1179
1180         if( ufn != NULL ) ldap_memfree( ufn );
1181         ldap_memfree( dn );
1182
1183         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1184                 a = ldap_next_attribute( ld, entry, ber ) )
1185         {
1186                 if ( attrsonly ) {
1187                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1188
1189                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1190                         for ( i = 0; bvals[i] != NULL; i++ ) {
1191                                 if ( vals2tmp > 1 || ( vals2tmp
1192                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1193                                 {
1194                                         int tmpfd;
1195                                         /* write value to file */
1196                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1197                                                 tmpdir, a );
1198                                         tmpfp = NULL;
1199
1200                                         tmpfd = mkstemp( tmpfname );
1201
1202                                         if ( tmpfd < 0  ) {
1203                                                 perror( tmpfname );
1204                                                 continue;
1205                                         }
1206
1207                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1208                                                 perror( tmpfname );
1209                                                 continue;
1210                                         }
1211
1212                                         if ( fwrite( bvals[ i ]->bv_val,
1213                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1214                                         {
1215                                                 perror( tmpfname );
1216                                                 fclose( tmpfp );
1217                                                 continue;
1218                                         }
1219
1220                                         fclose( tmpfp );
1221
1222                                         sprintf( url, "%s%s", urlpre,
1223                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1224
1225                                         urlize( url );
1226                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1227
1228                                 } else {
1229                                         write_ldif( LDIF_PUT_VALUE, a,
1230                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1231                                 }
1232                         }
1233                         ber_bvecfree( bvals );
1234                 }
1235         }
1236
1237         if( ber != NULL ) {
1238                 ber_free( ber, 0 );
1239         }
1240 }
1241
1242 static void print_reference(
1243         LDAP *ld,
1244         LDAPMessage *reference )
1245 {
1246         int rc;
1247         char **refs = NULL;
1248         LDAPControl **ctrls;
1249
1250         if( ldif < 2 ) {
1251                 printf("# search reference\n");
1252         }
1253
1254         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1255
1256         if( rc != LDAP_SUCCESS ) {
1257                 ldap_perror(ld, "ldap_parse_reference");
1258                 exit( EXIT_FAILURE );
1259         }
1260
1261         if( refs ) {
1262                 int i;
1263                 for( i=0; refs[i] != NULL; i++ ) {
1264                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1265                                 "ref", refs[i], strlen(refs[i]) );
1266                 }
1267                 ber_memvfree( (void **) refs );
1268         }
1269
1270         if( ctrls ) {
1271                 print_ctrls( ctrls );
1272                 ldap_controls_free( ctrls );
1273         }
1274 }
1275
1276 static void print_extended(
1277         LDAP *ld,
1278         LDAPMessage *extended )
1279 {
1280         int rc;
1281         char *retoid = NULL;
1282         struct berval *retdata = NULL;
1283
1284         if( ldif < 2 ) {
1285                 printf("# extended result response\n");
1286         }
1287
1288         rc = ldap_parse_extended_result( ld, extended,
1289                 &retoid, &retdata, 0 );
1290
1291         if( rc != LDAP_SUCCESS ) {
1292                 ldap_perror(ld, "ldap_parse_extended_result");
1293                 exit( EXIT_FAILURE );
1294         }
1295
1296         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1297                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1298         ber_memfree( retoid );
1299
1300         if(retdata) {
1301                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1302                         "data", retdata->bv_val, retdata->bv_len );
1303                 ber_bvfree( retdata );
1304         }
1305
1306         print_result( ld, extended, 0 );
1307 }
1308
1309 static void print_partial(
1310         LDAP *ld,
1311         LDAPMessage *partial )
1312 {
1313         int rc;
1314         char *retoid = NULL;
1315         struct berval *retdata = NULL;
1316         LDAPControl **ctrls = NULL;
1317
1318         if( ldif < 2 ) {
1319                 printf("# extended partial response\n");
1320         }
1321
1322         rc = ldap_parse_extended_partial( ld, partial,
1323                 &retoid, &retdata, &ctrls, 0 );
1324
1325         if( rc != LDAP_SUCCESS ) {
1326                 ldap_perror(ld, "ldap_parse_extended_partial");
1327                 exit( EXIT_FAILURE );
1328         }
1329
1330         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1331                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1332
1333         ber_memfree( retoid );
1334
1335         if( retdata ) {
1336                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1337                         "data", 
1338                         retdata->bv_val, retdata->bv_len );
1339
1340                 ber_bvfree( retdata );
1341         }
1342
1343         if( ctrls ) {
1344                 print_ctrls( ctrls );
1345                 ldap_controls_free( ctrls );
1346         }
1347 }
1348
1349 static int print_result(
1350         LDAP *ld,
1351         LDAPMessage *result, int search )
1352 {
1353         int rc;
1354         int err;
1355         char *matcheddn = NULL;
1356         char *text = NULL;
1357         char **refs = NULL;
1358         LDAPControl **ctrls = NULL;
1359
1360         if( search ) {
1361                 if ( ldif < 2 ) {
1362                         printf("# search result\n");
1363                 }
1364                 if ( ldif < 1 ) {
1365                         printf("%s: %d\n", "search", ldap_msgid(result) );
1366                 }
1367         }
1368
1369         rc = ldap_parse_result( ld, result,
1370                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1371
1372         if( rc != LDAP_SUCCESS ) {
1373                 ldap_perror(ld, "ldap_parse_result");
1374                 exit( EXIT_FAILURE );
1375         }
1376
1377
1378         if( !ldif ) {
1379                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1380
1381         } else if ( err != LDAP_SUCCESS ) {
1382                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1383         }
1384
1385         if( matcheddn && *matcheddn ) {
1386                 if( !ldif ) {
1387                         write_ldif( LDIF_PUT_VALUE,
1388                                 "matchedDN", matcheddn, strlen(matcheddn) );
1389                 } else {
1390                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1391                 }
1392
1393                 ber_memfree( matcheddn );
1394         }
1395
1396         if( text && *text ) {
1397                 if( !ldif ) {
1398                         write_ldif( LDIF_PUT_TEXT, "text",
1399                                 text, strlen(text) );
1400                 } else {
1401                         fprintf( stderr, "Additional information: %s\n", text );
1402                 }
1403
1404                 ber_memfree( text );
1405         }
1406
1407         if( refs ) {
1408                 int i;
1409                 for( i=0; refs[i] != NULL; i++ ) {
1410                         if( !ldif ) {
1411                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1412                         } else {
1413                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1414                         }
1415                 }
1416
1417                 ber_memvfree( (void **) refs );
1418         }
1419
1420         if( ctrls ) {
1421                 print_ctrls( ctrls );
1422                 ldap_controls_free( ctrls );
1423         }
1424
1425         return err;
1426 }
1427
1428 static void print_ctrls(
1429         LDAPControl **ctrls )
1430 {
1431         int i;
1432         for(i=0; ctrls[i] != NULL; i++ ) {
1433                 /* control: OID criticality base64value */
1434                 struct berval *b64 = NULL;
1435                 ber_len_t len;
1436                 char *str;
1437                         
1438                 len = strlen( ctrls[i]->ldctl_oid );
1439
1440                 /* add enough for space after OID and the critical value itself */
1441                 len += ctrls[i]->ldctl_iscritical
1442                         ? sizeof("true") : sizeof("false");
1443
1444                 /* convert to base64 */
1445                 if( ctrls[i]->ldctl_value.bv_len ) {
1446                         b64 = ber_memalloc( sizeof(struct berval) );
1447                         
1448                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1449                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1450                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1451
1452                         b64->bv_len = lutil_b64_ntop(
1453                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1454                                 b64->bv_val, b64->bv_len );
1455                 }
1456
1457                 if( b64 ) {
1458                         len += 1 + b64->bv_len;
1459                 }
1460
1461                 str = malloc( len + 1 );
1462                 strcpy( str, ctrls[i]->ldctl_oid );
1463                 strcat( str, ctrls[i]->ldctl_iscritical
1464                         ? " true" : " false" );
1465
1466                 if( b64 ) {
1467                         strcat(str, " ");
1468                         strcat(str, b64->bv_val );
1469                 }
1470
1471                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1472                         "control", str, len );
1473
1474                 free( str );
1475                 ber_bvfree( b64 );
1476         }
1477 }
1478
1479 static int
1480 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1481 {
1482         char    *ldif;
1483
1484         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1485                 return( -1 );
1486         }
1487
1488         fputs( ldif, stdout );
1489         ber_memfree( ldif );
1490
1491         return( 0 );
1492 }