]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Add more LDIF comments
[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"
1091                         "# LDAPv%d\n"
1092                         "# base <%s> with scope %s\n"
1093                         "# filter%s: %s\n"
1094                         "# requesting: ",
1095                         version,
1096                         base, (scope == LDAP_SCOPE_BASE) ? "base"
1097                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
1098                         infile != NULL ? " pattern" : "",
1099                         filtpattern );
1100
1101                 if ( attrs == NULL ) {
1102                         printf( "ALL" );
1103                 } else {
1104                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1105                                 printf( "%s ", attrs[ i ] );
1106                         }
1107                 }
1108
1109                 if ( manageDSAit ) {
1110                         printf("\n# with manageDSAit %scontrol",
1111                                 manageDSAit > 1 ? "critical " : "" );
1112                 }
1113                 if ( noop ) {
1114                         printf("\n# with noop %scontrol",
1115                                 noop > 1 ? "critical " : "" );
1116                 }
1117                 if ( subentries ) {
1118                         printf("\n# with subentries %scontrol: %s",
1119                                 subentries < 0 ? "critical " : "",
1120                                 abs(subentries) == 1 ? "false" : "true" );
1121                 }
1122                 if ( valuesReturnFilter ) {
1123                         printf("\n# with valuesReturnFilter %scontrol: %s",
1124                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
1125                 }
1126
1127                 printf( "\n#\n\n" );
1128         }
1129
1130         if ( infile == NULL ) {
1131                 rc = dosearch( ld, base, scope, NULL, filtpattern,
1132                         attrs, attrsonly, NULL, NULL, NULL, -1 );
1133
1134         } else {
1135                 rc = 0;
1136                 first = 1;
1137                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
1138                         line[ strlen( line ) - 1 ] = '\0';
1139                         if ( !first ) {
1140                                 putchar( '\n' );
1141                         } else {
1142                                 first = 0;
1143                         }
1144                         rc = dosearch( ld, base, scope, filtpattern, line,
1145                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1146                 }
1147                 if ( fp != stdin ) {
1148                         fclose( fp );
1149                 }
1150         }
1151
1152         ldap_unbind( ld );
1153         return( rc );
1154 }
1155
1156
1157 static int dosearch(
1158         LDAP    *ld,
1159         char    *base,
1160         int             scope,
1161         char    *filtpatt,
1162         char    *value,
1163         char    **attrs,
1164         int             attrsonly,
1165         LDAPControl **sctrls,
1166         LDAPControl **cctrls,
1167         struct timeval *timeout,
1168         int sizelimit )
1169 {
1170         char                    *filter;
1171         int                     rc;
1172         int                     nresponses;
1173         int                     nentries;
1174         int                     nreferences;
1175         int                     nextended;
1176         int                     npartial;
1177         LDAPMessage             *res, *msg;
1178         ber_int_t       msgid;
1179
1180         if( filtpatt != NULL ) {
1181                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1182                 if( filter == NULL ) {
1183                         perror( "malloc" );
1184                         return EXIT_FAILURE;
1185                 }
1186
1187                 sprintf( filter, filtpatt, value );
1188
1189                 if ( verbose ) {
1190                         fprintf( stderr, "filter: %s\n", filter );
1191                 }
1192
1193                 if( ldif < 2 ) {
1194                         printf( "#\n# filter: %s\n#\n", filter );
1195                 }
1196
1197         } else {
1198                 filter = value;
1199         }
1200
1201         if ( not ) {
1202                 return LDAP_SUCCESS;
1203         }
1204
1205         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1206                 sctrls, cctrls, timeout, sizelimit, &msgid );
1207
1208         if ( filtpatt != NULL ) {
1209                 free( filter );
1210         }
1211
1212         if( rc != LDAP_SUCCESS ) {
1213                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1214                         prog, ldap_err2string( rc ), rc );
1215                 return( rc );
1216         }
1217
1218         nresponses = nentries = nreferences = nextended = npartial = 0;
1219
1220         res = NULL;
1221
1222         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1223                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1224                 NULL, &res )) > 0 )
1225         {
1226                 if( sortattr ) {
1227                         (void) ldap_sort_entries( ld, &res,
1228                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1229                 }
1230
1231                 for ( msg = ldap_first_message( ld, res );
1232                         msg != NULL;
1233                         msg = ldap_next_message( ld, msg ) )
1234                 {
1235                         if( nresponses++ ) putchar('\n');
1236
1237                         switch( ldap_msgtype( msg ) ) {
1238                         case LDAP_RES_SEARCH_ENTRY:
1239                                 nentries++;
1240                                 print_entry( ld, msg, attrsonly );
1241                                 break;
1242
1243                         case LDAP_RES_SEARCH_REFERENCE:
1244                                 nreferences++;
1245                                 print_reference( ld, msg );
1246                                 break;
1247
1248                         case LDAP_RES_EXTENDED:
1249                                 nextended++;
1250                                 print_extended( ld, msg );
1251
1252                                 if( ldap_msgid( msg ) == 0 ) {
1253                                         /* unsolicited extended operation */
1254                                         goto done;
1255                                 }
1256                                 break;
1257
1258                         case LDAP_RES_EXTENDED_PARTIAL:
1259                                 npartial++;
1260                                 print_partial( ld, msg );
1261                                 break;
1262
1263                         case LDAP_RES_SEARCH_RESULT:
1264                                 rc = print_result( ld, msg, 1 );
1265                                 goto done;
1266                         }
1267                 }
1268
1269                 ldap_msgfree( res );
1270         }
1271
1272         if ( rc == -1 ) {
1273                 ldap_perror( ld, "ldap_result" );
1274                 return( rc );
1275         }
1276
1277 done:
1278         if ( ldif < 2 ) {
1279                 printf( "\n# numResponses: %d\n", nresponses );
1280                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1281                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1282                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1283                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1284         }
1285
1286         return( rc );
1287 }
1288
1289 #if 1
1290 /* This is the original version, the old way of doing things. */
1291 static void
1292 print_entry(
1293         LDAP    *ld,
1294         LDAPMessage     *entry,
1295         int             attrsonly)
1296 {
1297         char            *a, *dn, *ufn;
1298         char    tmpfname[ 256 ];
1299         char    url[ 256 ];
1300         int                     i, rc;
1301         BerElement              *ber = NULL;
1302         struct berval   **bvals;
1303         LDAPControl **ctrls = NULL;
1304         FILE            *tmpfp;
1305
1306         dn = ldap_get_dn( ld, entry );
1307         ufn = NULL;
1308
1309         if ( ldif < 2 ) {
1310                 ufn = ldap_dn2ufn( dn );
1311                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1312         }
1313         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1314
1315         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1316
1317         if( rc != LDAP_SUCCESS ) {
1318                 fprintf(stderr, "print_entry: %d\n", rc );
1319                 ldap_perror( ld, "ldap_get_entry_controls" );
1320                 exit( EXIT_FAILURE );
1321         }
1322
1323         if( ctrls ) {
1324                 print_ctrls( ctrls );
1325                 ldap_controls_free( ctrls );
1326         }
1327
1328         if ( includeufn ) {
1329                 if( ufn == NULL ) {
1330                         ufn = ldap_dn2ufn( dn );
1331                 }
1332                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1333         }
1334
1335         if( ufn != NULL ) ldap_memfree( ufn );
1336         ldap_memfree( dn );
1337
1338         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1339                 a = ldap_next_attribute( ld, entry, ber ) )
1340         {
1341                 if ( attrsonly ) {
1342                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1343
1344                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1345                         for ( i = 0; bvals[i] != NULL; i++ ) {
1346                                 if ( vals2tmp > 1 || ( vals2tmp
1347                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1348                                 {
1349                                         int tmpfd;
1350                                         /* write value to file */
1351                                         snprintf( tmpfname, sizeof tmpfname,
1352                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1353                                                 tmpdir, a );
1354                                         tmpfp = NULL;
1355
1356                                         tmpfd = mkstemp( tmpfname );
1357
1358                                         if ( tmpfd < 0  ) {
1359                                                 perror( tmpfname );
1360                                                 continue;
1361                                         }
1362
1363                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1364                                                 perror( tmpfname );
1365                                                 continue;
1366                                         }
1367
1368                                         if ( fwrite( bvals[ i ]->bv_val,
1369                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1370                                         {
1371                                                 perror( tmpfname );
1372                                                 fclose( tmpfp );
1373                                                 continue;
1374                                         }
1375
1376                                         fclose( tmpfp );
1377
1378                                         snprintf( url, sizeof url, "%s%s", urlpre,
1379                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1380
1381                                         urlize( url );
1382                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1383
1384                                 } else {
1385                                         write_ldif( LDIF_PUT_VALUE, a,
1386                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1387                                 }
1388                         }
1389                         ber_bvecfree( bvals );
1390                 }
1391         }
1392
1393         if( ber != NULL ) {
1394                 ber_free( ber, 0 );
1395         }
1396 }
1397 #else
1398 /* This is the proposed new way of doing things.
1399  * It is more * efficient, but the API is non-standard.
1400  */
1401 static void
1402 print_entry(
1403         LDAP    *ld,
1404         LDAPMessage     *entry,
1405         int             attrsonly)
1406 {
1407         char            *ufn = NULL;
1408         char    tmpfname[ 256 ];
1409         char    url[ 256 ];
1410         int                     i, rc;
1411         BerElement              *ber = NULL;
1412         struct berval           bv, *bvals, **bvp = &bvals;
1413         LDAPControl **ctrls = NULL;
1414         FILE            *tmpfp;
1415
1416         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1417
1418         if ( ldif < 2 ) {
1419                 ufn = ldap_dn2ufn( bv.bv_val );
1420                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1421         }
1422         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1423
1424         rc = ldap_int_get_controls( ber, &ctrls );
1425
1426         if( rc != LDAP_SUCCESS ) {
1427                 fprintf(stderr, "print_entry: %d\n", rc );
1428                 ldap_perror( ld, "ldap_get_entry_controls" );
1429                 exit( EXIT_FAILURE );
1430         }
1431
1432         if( ctrls ) {
1433                 print_ctrls( ctrls );
1434                 ldap_controls_free( ctrls );
1435         }
1436
1437         if ( includeufn ) {
1438                 if( ufn == NULL ) {
1439                         ufn = ldap_dn2ufn( bv.bv_val );
1440                 }
1441                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1442         }
1443
1444         if( ufn != NULL ) ldap_memfree( ufn );
1445
1446         if ( attrsonly ) bvp = NULL;
1447
1448         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ); rc == LDAP_SUCCESS;
1449                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1450         {
1451                 if (bv.bv_val == NULL) break;
1452
1453                 if ( attrsonly ) {
1454                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1455
1456                 } else {
1457                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1458                                 if ( vals2tmp > 1 || ( vals2tmp
1459                                         && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1460                                 {
1461                                         int tmpfd;
1462                                         /* write value to file */
1463                                         snprintf( tmpfname, sizeof tmpfname,
1464                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1465                                                 tmpdir, bv.bv_val );
1466                                         tmpfp = NULL;
1467
1468                                         tmpfd = mkstemp( tmpfname );
1469
1470                                         if ( tmpfd < 0  ) {
1471                                                 perror( tmpfname );
1472                                                 continue;
1473                                         }
1474
1475                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1476                                                 perror( tmpfname );
1477                                                 continue;
1478                                         }
1479
1480                                         if ( fwrite( bvals[ i ].bv_val,
1481                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1482                                         {
1483                                                 perror( tmpfname );
1484                                                 fclose( tmpfp );
1485                                                 continue;
1486                                         }
1487
1488                                         fclose( tmpfp );
1489
1490                                         snprintf( url, sizeof url, "%s%s", urlpre,
1491                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1492
1493                                         urlize( url );
1494                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1495
1496                                 } else {
1497                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1498                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1499                                 }
1500                         }
1501                         ber_memfree( bvals );
1502                 }
1503         }
1504
1505         if( ber != NULL ) {
1506                 ber_free( ber, 0 );
1507         }
1508 }
1509 #endif
1510
1511 static void print_reference(
1512         LDAP *ld,
1513         LDAPMessage *reference )
1514 {
1515         int rc;
1516         char **refs = NULL;
1517         LDAPControl **ctrls;
1518
1519         if( ldif < 2 ) {
1520                 printf("# search reference\n");
1521         }
1522
1523         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1524
1525         if( rc != LDAP_SUCCESS ) {
1526                 ldap_perror(ld, "ldap_parse_reference");
1527                 exit( EXIT_FAILURE );
1528         }
1529
1530         if( refs ) {
1531                 int i;
1532                 for( i=0; refs[i] != NULL; i++ ) {
1533                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1534                                 "ref", refs[i], strlen(refs[i]) );
1535                 }
1536                 ber_memvfree( (void **) refs );
1537         }
1538
1539         if( ctrls ) {
1540                 print_ctrls( ctrls );
1541                 ldap_controls_free( ctrls );
1542         }
1543 }
1544
1545 static void print_extended(
1546         LDAP *ld,
1547         LDAPMessage *extended )
1548 {
1549         int rc;
1550         char *retoid = NULL;
1551         struct berval *retdata = NULL;
1552
1553         if( ldif < 2 ) {
1554                 printf("# extended result response\n");
1555         }
1556
1557         rc = ldap_parse_extended_result( ld, extended,
1558                 &retoid, &retdata, 0 );
1559
1560         if( rc != LDAP_SUCCESS ) {
1561                 ldap_perror(ld, "ldap_parse_extended_result");
1562                 exit( EXIT_FAILURE );
1563         }
1564
1565         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1566                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1567         ber_memfree( retoid );
1568
1569         if(retdata) {
1570                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1571                         "data", retdata->bv_val, retdata->bv_len );
1572                 ber_bvfree( retdata );
1573         }
1574
1575         print_result( ld, extended, 0 );
1576 }
1577
1578 static void print_partial(
1579         LDAP *ld,
1580         LDAPMessage *partial )
1581 {
1582         int rc;
1583         char *retoid = NULL;
1584         struct berval *retdata = NULL;
1585         LDAPControl **ctrls = NULL;
1586
1587         if( ldif < 2 ) {
1588                 printf("# extended partial response\n");
1589         }
1590
1591         rc = ldap_parse_extended_partial( ld, partial,
1592                 &retoid, &retdata, &ctrls, 0 );
1593
1594         if( rc != LDAP_SUCCESS ) {
1595                 ldap_perror(ld, "ldap_parse_extended_partial");
1596                 exit( EXIT_FAILURE );
1597         }
1598
1599         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1600                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1601
1602         ber_memfree( retoid );
1603
1604         if( retdata ) {
1605                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1606                         "data", 
1607                         retdata->bv_val, retdata->bv_len );
1608
1609                 ber_bvfree( retdata );
1610         }
1611
1612         if( ctrls ) {
1613                 print_ctrls( ctrls );
1614                 ldap_controls_free( ctrls );
1615         }
1616 }
1617
1618 static int print_result(
1619         LDAP *ld,
1620         LDAPMessage *result, int search )
1621 {
1622         int rc;
1623         int err;
1624         char *matcheddn = NULL;
1625         char *text = NULL;
1626         char **refs = NULL;
1627         LDAPControl **ctrls = NULL;
1628
1629         if( search ) {
1630                 if ( ldif < 2 ) {
1631                         printf("# search result\n");
1632                 }
1633                 if ( ldif < 1 ) {
1634                         printf("%s: %d\n", "search", ldap_msgid(result) );
1635                 }
1636         }
1637
1638         rc = ldap_parse_result( ld, result,
1639                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1640
1641         if( rc != LDAP_SUCCESS ) {
1642                 ldap_perror(ld, "ldap_parse_result");
1643                 exit( EXIT_FAILURE );
1644         }
1645
1646
1647         if( !ldif ) {
1648                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1649
1650         } else if ( err != LDAP_SUCCESS ) {
1651                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1652         }
1653
1654         if( matcheddn && *matcheddn ) {
1655                 if( !ldif ) {
1656                         write_ldif( LDIF_PUT_VALUE,
1657                                 "matchedDN", matcheddn, strlen(matcheddn) );
1658                 } else {
1659                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1660                 }
1661
1662                 ber_memfree( matcheddn );
1663         }
1664
1665         if( text && *text ) {
1666                 if( !ldif ) {
1667                         write_ldif( LDIF_PUT_TEXT, "text",
1668                                 text, strlen(text) );
1669                 } else {
1670                         fprintf( stderr, "Additional information: %s\n", text );
1671                 }
1672
1673                 ber_memfree( text );
1674         }
1675
1676         if( refs ) {
1677                 int i;
1678                 for( i=0; refs[i] != NULL; i++ ) {
1679                         if( !ldif ) {
1680                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1681                         } else {
1682                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1683                         }
1684                 }
1685
1686                 ber_memvfree( (void **) refs );
1687         }
1688
1689         if( ctrls ) {
1690                 print_ctrls( ctrls );
1691                 ldap_controls_free( ctrls );
1692         }
1693
1694         return err;
1695 }
1696
1697 static void print_ctrls(
1698         LDAPControl **ctrls )
1699 {
1700         int i;
1701         for(i=0; ctrls[i] != NULL; i++ ) {
1702                 /* control: OID criticality base64value */
1703                 struct berval *b64 = NULL;
1704                 ber_len_t len;
1705                 char *str;
1706                         
1707                 len = strlen( ctrls[i]->ldctl_oid );
1708
1709                 /* add enough for space after OID and the critical value itself */
1710                 len += ctrls[i]->ldctl_iscritical
1711                         ? sizeof("true") : sizeof("false");
1712
1713                 /* convert to base64 */
1714                 if( ctrls[i]->ldctl_value.bv_len ) {
1715                         b64 = ber_memalloc( sizeof(struct berval) );
1716                         
1717                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1718                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1719                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1720
1721                         b64->bv_len = lutil_b64_ntop(
1722                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1723                                 b64->bv_val, b64->bv_len );
1724                 }
1725
1726                 if( b64 ) {
1727                         len += 1 + b64->bv_len;
1728                 }
1729
1730                 str = malloc( len + 1 );
1731                 strcpy( str, ctrls[i]->ldctl_oid );
1732                 strcat( str, ctrls[i]->ldctl_iscritical
1733                         ? " true" : " false" );
1734
1735                 if( b64 ) {
1736                         strcat(str, " ");
1737                         strcat(str, b64->bv_val );
1738                 }
1739
1740                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1741                         "control", str, len );
1742
1743                 free( str );
1744                 ber_bvfree( b64 );
1745         }
1746 }
1747
1748 static int
1749 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1750 {
1751         char    *ldif;
1752
1753         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1754                 return( -1 );
1755         }
1756
1757         fputs( ldif, stdout );
1758         ber_memfree( ldif );
1759
1760         return( 0 );
1761 }