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