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