]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Add client-side subentries control support.
[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;
980                 LDAPControl *ctrls[4];
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                 if ( valuesReturnFilter ) {
1003                         ctrls[i++]=&c3;
1004                         ctrls[i] = NULL;
1005
1006                         c3.ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
1007                         c3.ldctl_iscritical = valuesReturnFilter > 1;
1008                     
1009                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1010                                 return EXIT_FAILURE;
1011                         }
1012
1013                 if ( ( err = ldap_put_vrFilter( ber, vrFilter ) ) == -1 ) {
1014                                 ber_free( ber, 1 );
1015                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
1016                                 return EXIT_FAILURE;
1017                         }
1018
1019                         if ( ber_flatten( ber, &bvalp ) == LBER_ERROR ) {
1020                                 return EXIT_FAILURE;
1021                         }
1022
1023                         c3.ldctl_value=(*bvalp);
1024                 }
1025
1026                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1027
1028                 ber_bvfree(bvalp);
1029                 ber_free( ber, 1 );
1030
1031                 if( err != LDAP_OPT_SUCCESS ) {
1032                         fprintf( stderr, "Could not set %scontrols\n",
1033                                 (c1.ldctl_iscritical || c2.ldctl_iscritical)
1034                                 ? "critical " : "" );
1035                         if( c1.ldctl_iscritical && c2.ldctl_iscritical ) {
1036                                 return EXIT_FAILURE;
1037                         }
1038                 }
1039         }
1040         
1041         if ( verbose ) {
1042                 fprintf( stderr, "filter%s: %s\nrequesting: ",
1043                         infile != NULL ? " pattern" : "",
1044                         filtpattern );
1045
1046                 if ( attrs == NULL ) {
1047                         fprintf( stderr, "ALL" );
1048                 } else {
1049                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1050                                 fprintf( stderr, "%s ", attrs[ i ] );
1051                         }
1052                 }
1053                 fprintf( stderr, "\n" );
1054         }
1055
1056         if ( ldif == 0 ) {
1057                 printf( "# extended LDIF\n" );
1058         } else if ( ldif < 3 ) {
1059                 printf( "version: %d\n\n", 1 );
1060         }
1061
1062         if (ldif < 2 ) {
1063                 printf( "#\n# LDAPv%d\n# filter%s: %s\n# requesting: ",
1064                         version,
1065                         infile != NULL ? " pattern" : "",
1066                         filtpattern );
1067
1068                 if ( attrs == NULL ) {
1069                         printf( "ALL" );
1070                 } else {
1071                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1072                                 printf( "%s ", attrs[ i ] );
1073                         }
1074                 }
1075
1076                 if ( manageDSAit ) {
1077                         printf("\n# with manageDSAit %scontrol",
1078                                 manageDSAit > 1 ? "critical " : "" );
1079                 }
1080                 if ( noop ) {
1081                         printf("\n# with noop %scontrol",
1082                                 noop > 1 ? "critical " : "" );
1083                 }
1084                 if ( subentries ) {
1085                         printf("\n# with subentries %scontrol: %s",
1086                                 subentries < 0 ? "critical " : "",
1087                                 abs(subentries) == 1 ? "false" : "true" );
1088                 }
1089                 if ( valuesReturnFilter ) {
1090                         printf("\n# with valuesReturnFilter %scontrol: %s",
1091                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
1092                 }
1093
1094                 printf( "\n#\n\n" );
1095         }
1096
1097         if ( infile == NULL ) {
1098                 rc = dosearch( ld, base, scope, NULL, filtpattern,
1099                         attrs, attrsonly, NULL, NULL, NULL, -1 );
1100
1101         } else {
1102                 rc = 0;
1103                 first = 1;
1104                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
1105                         line[ strlen( line ) - 1 ] = '\0';
1106                         if ( !first ) {
1107                                 putchar( '\n' );
1108                         } else {
1109                                 first = 0;
1110                         }
1111                         rc = dosearch( ld, base, scope, filtpattern, line,
1112                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1113                 }
1114                 if ( fp != stdin ) {
1115                         fclose( fp );
1116                 }
1117         }
1118
1119         ldap_unbind( ld );
1120         return( rc );
1121 }
1122
1123
1124 static int dosearch(
1125         LDAP    *ld,
1126         char    *base,
1127         int             scope,
1128         char    *filtpatt,
1129         char    *value,
1130         char    **attrs,
1131         int             attrsonly,
1132         LDAPControl **sctrls,
1133         LDAPControl **cctrls,
1134         struct timeval *timeout,
1135         int sizelimit )
1136 {
1137         char                    *filter;
1138         int                     rc;
1139         int                     nresponses;
1140         int                     nentries;
1141         int                     nreferences;
1142         int                     nextended;
1143         int                     npartial;
1144         LDAPMessage             *res, *msg;
1145         ber_int_t       msgid;
1146
1147         if( filtpatt != NULL ) {
1148                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1149                 if( filter == NULL ) {
1150                         perror( "malloc" );
1151                         return EXIT_FAILURE;
1152                 }
1153
1154                 sprintf( filter, filtpatt, value );
1155
1156                 if ( verbose ) {
1157                         fprintf( stderr, "filter: %s\n", filter );
1158                 }
1159
1160                 if( ldif < 2 ) {
1161                         printf( "#\n# filter: %s\n#\n", filter );
1162                 }
1163
1164         } else {
1165                 filter = value;
1166         }
1167
1168         if ( not ) {
1169                 return LDAP_SUCCESS;
1170         }
1171
1172         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1173                 sctrls, cctrls, timeout, sizelimit, &msgid );
1174
1175         if ( filtpatt != NULL ) {
1176                 free( filter );
1177         }
1178
1179         if( rc != LDAP_SUCCESS ) {
1180                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1181                         prog, ldap_err2string( rc ), rc );
1182                 return( rc );
1183         }
1184
1185         nresponses = nentries = nreferences = nextended = npartial = 0;
1186
1187         res = NULL;
1188
1189         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1190                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1191                 NULL, &res )) > 0 )
1192         {
1193                 if( sortattr ) {
1194                         (void) ldap_sort_entries( ld, &res,
1195                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1196                 }
1197
1198                 for ( msg = ldap_first_message( ld, res );
1199                         msg != NULL;
1200                         msg = ldap_next_message( ld, msg ) )
1201                 {
1202                         if( nresponses++ ) putchar('\n');
1203
1204                         switch( ldap_msgtype( msg ) ) {
1205                         case LDAP_RES_SEARCH_ENTRY:
1206                                 nentries++;
1207                                 print_entry( ld, msg, attrsonly );
1208                                 break;
1209
1210                         case LDAP_RES_SEARCH_REFERENCE:
1211                                 nreferences++;
1212                                 print_reference( ld, msg );
1213                                 break;
1214
1215                         case LDAP_RES_EXTENDED:
1216                                 nextended++;
1217                                 print_extended( ld, msg );
1218
1219                                 if( ldap_msgid( msg ) == 0 ) {
1220                                         /* unsolicited extended operation */
1221                                         goto done;
1222                                 }
1223                                 break;
1224
1225                         case LDAP_RES_EXTENDED_PARTIAL:
1226                                 npartial++;
1227                                 print_partial( ld, msg );
1228                                 break;
1229
1230                         case LDAP_RES_SEARCH_RESULT:
1231                                 rc = print_result( ld, msg, 1 );
1232                                 goto done;
1233                         }
1234                 }
1235
1236                 ldap_msgfree( res );
1237         }
1238
1239         if ( rc == -1 ) {
1240                 ldap_perror( ld, "ldap_result" );
1241                 return( rc );
1242         }
1243
1244 done:
1245         if ( ldif < 2 ) {
1246                 printf( "\n# numResponses: %d\n", nresponses );
1247                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1248                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1249                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1250                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1251         }
1252
1253         return( rc );
1254 }
1255
1256 static void
1257 print_entry(
1258         LDAP    *ld,
1259         LDAPMessage     *entry,
1260         int             attrsonly)
1261 {
1262         char            *a, *dn, *ufn;
1263         char    tmpfname[ 256 ];
1264         char    url[ 256 ];
1265         int                     i, rc;
1266         BerElement              *ber = NULL;
1267         struct berval   **bvals;
1268         LDAPControl **ctrls = NULL;
1269         FILE            *tmpfp;
1270
1271         dn = ldap_get_dn( ld, entry );
1272         ufn = NULL;
1273
1274         if ( ldif < 2 ) {
1275                 ufn = ldap_dn2ufn( dn );
1276                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1277         }
1278         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1279
1280         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1281
1282         if( rc != LDAP_SUCCESS ) {
1283                 fprintf(stderr, "print_entry: %d\n", rc );
1284                 ldap_perror( ld, "ldap_get_entry_controls" );
1285                 exit( EXIT_FAILURE );
1286         }
1287
1288         if( ctrls ) {
1289                 print_ctrls( ctrls );
1290                 ldap_controls_free( ctrls );
1291         }
1292
1293         if ( includeufn ) {
1294                 if( ufn == NULL ) {
1295                         ufn = ldap_dn2ufn( dn );
1296                 }
1297                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1298         }
1299
1300         if( ufn != NULL ) ldap_memfree( ufn );
1301         ldap_memfree( dn );
1302
1303         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1304                 a = ldap_next_attribute( ld, entry, ber ) )
1305         {
1306                 if ( attrsonly ) {
1307                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1308
1309                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1310                         for ( i = 0; bvals[i] != NULL; i++ ) {
1311                                 if ( vals2tmp > 1 || ( vals2tmp
1312                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1313                                 {
1314                                         int tmpfd;
1315                                         /* write value to file */
1316                                         snprintf( tmpfname, sizeof tmpfname,
1317                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1318                                                 tmpdir, a );
1319                                         tmpfp = NULL;
1320
1321                                         tmpfd = mkstemp( tmpfname );
1322
1323                                         if ( tmpfd < 0  ) {
1324                                                 perror( tmpfname );
1325                                                 continue;
1326                                         }
1327
1328                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1329                                                 perror( tmpfname );
1330                                                 continue;
1331                                         }
1332
1333                                         if ( fwrite( bvals[ i ]->bv_val,
1334                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1335                                         {
1336                                                 perror( tmpfname );
1337                                                 fclose( tmpfp );
1338                                                 continue;
1339                                         }
1340
1341                                         fclose( tmpfp );
1342
1343                                         snprintf( url, sizeof url, "%s%s", urlpre,
1344                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1345
1346                                         urlize( url );
1347                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1348
1349                                 } else {
1350                                         write_ldif( LDIF_PUT_VALUE, a,
1351                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1352                                 }
1353                         }
1354                         ber_bvecfree( bvals );
1355                 }
1356         }
1357
1358         if( ber != NULL ) {
1359                 ber_free( ber, 0 );
1360         }
1361 }
1362
1363 static void print_reference(
1364         LDAP *ld,
1365         LDAPMessage *reference )
1366 {
1367         int rc;
1368         char **refs = NULL;
1369         LDAPControl **ctrls;
1370
1371         if( ldif < 2 ) {
1372                 printf("# search reference\n");
1373         }
1374
1375         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1376
1377         if( rc != LDAP_SUCCESS ) {
1378                 ldap_perror(ld, "ldap_parse_reference");
1379                 exit( EXIT_FAILURE );
1380         }
1381
1382         if( refs ) {
1383                 int i;
1384                 for( i=0; refs[i] != NULL; i++ ) {
1385                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1386                                 "ref", refs[i], strlen(refs[i]) );
1387                 }
1388                 ber_memvfree( (void **) refs );
1389         }
1390
1391         if( ctrls ) {
1392                 print_ctrls( ctrls );
1393                 ldap_controls_free( ctrls );
1394         }
1395 }
1396
1397 static void print_extended(
1398         LDAP *ld,
1399         LDAPMessage *extended )
1400 {
1401         int rc;
1402         char *retoid = NULL;
1403         struct berval *retdata = NULL;
1404
1405         if( ldif < 2 ) {
1406                 printf("# extended result response\n");
1407         }
1408
1409         rc = ldap_parse_extended_result( ld, extended,
1410                 &retoid, &retdata, 0 );
1411
1412         if( rc != LDAP_SUCCESS ) {
1413                 ldap_perror(ld, "ldap_parse_extended_result");
1414                 exit( EXIT_FAILURE );
1415         }
1416
1417         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1418                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1419         ber_memfree( retoid );
1420
1421         if(retdata) {
1422                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1423                         "data", retdata->bv_val, retdata->bv_len );
1424                 ber_bvfree( retdata );
1425         }
1426
1427         print_result( ld, extended, 0 );
1428 }
1429
1430 static void print_partial(
1431         LDAP *ld,
1432         LDAPMessage *partial )
1433 {
1434         int rc;
1435         char *retoid = NULL;
1436         struct berval *retdata = NULL;
1437         LDAPControl **ctrls = NULL;
1438
1439         if( ldif < 2 ) {
1440                 printf("# extended partial response\n");
1441         }
1442
1443         rc = ldap_parse_extended_partial( ld, partial,
1444                 &retoid, &retdata, &ctrls, 0 );
1445
1446         if( rc != LDAP_SUCCESS ) {
1447                 ldap_perror(ld, "ldap_parse_extended_partial");
1448                 exit( EXIT_FAILURE );
1449         }
1450
1451         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1452                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1453
1454         ber_memfree( retoid );
1455
1456         if( retdata ) {
1457                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1458                         "data", 
1459                         retdata->bv_val, retdata->bv_len );
1460
1461                 ber_bvfree( retdata );
1462         }
1463
1464         if( ctrls ) {
1465                 print_ctrls( ctrls );
1466                 ldap_controls_free( ctrls );
1467         }
1468 }
1469
1470 static int print_result(
1471         LDAP *ld,
1472         LDAPMessage *result, int search )
1473 {
1474         int rc;
1475         int err;
1476         char *matcheddn = NULL;
1477         char *text = NULL;
1478         char **refs = NULL;
1479         LDAPControl **ctrls = NULL;
1480
1481         if( search ) {
1482                 if ( ldif < 2 ) {
1483                         printf("# search result\n");
1484                 }
1485                 if ( ldif < 1 ) {
1486                         printf("%s: %d\n", "search", ldap_msgid(result) );
1487                 }
1488         }
1489
1490         rc = ldap_parse_result( ld, result,
1491                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1492
1493         if( rc != LDAP_SUCCESS ) {
1494                 ldap_perror(ld, "ldap_parse_result");
1495                 exit( EXIT_FAILURE );
1496         }
1497
1498
1499         if( !ldif ) {
1500                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1501
1502         } else if ( err != LDAP_SUCCESS ) {
1503                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1504         }
1505
1506         if( matcheddn && *matcheddn ) {
1507                 if( !ldif ) {
1508                         write_ldif( LDIF_PUT_VALUE,
1509                                 "matchedDN", matcheddn, strlen(matcheddn) );
1510                 } else {
1511                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1512                 }
1513
1514                 ber_memfree( matcheddn );
1515         }
1516
1517         if( text && *text ) {
1518                 if( !ldif ) {
1519                         write_ldif( LDIF_PUT_TEXT, "text",
1520                                 text, strlen(text) );
1521                 } else {
1522                         fprintf( stderr, "Additional information: %s\n", text );
1523                 }
1524
1525                 ber_memfree( text );
1526         }
1527
1528         if( refs ) {
1529                 int i;
1530                 for( i=0; refs[i] != NULL; i++ ) {
1531                         if( !ldif ) {
1532                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1533                         } else {
1534                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1535                         }
1536                 }
1537
1538                 ber_memvfree( (void **) refs );
1539         }
1540
1541         if( ctrls ) {
1542                 print_ctrls( ctrls );
1543                 ldap_controls_free( ctrls );
1544         }
1545
1546         return err;
1547 }
1548
1549 static void print_ctrls(
1550         LDAPControl **ctrls )
1551 {
1552         int i;
1553         for(i=0; ctrls[i] != NULL; i++ ) {
1554                 /* control: OID criticality base64value */
1555                 struct berval *b64 = NULL;
1556                 ber_len_t len;
1557                 char *str;
1558                         
1559                 len = strlen( ctrls[i]->ldctl_oid );
1560
1561                 /* add enough for space after OID and the critical value itself */
1562                 len += ctrls[i]->ldctl_iscritical
1563                         ? sizeof("true") : sizeof("false");
1564
1565                 /* convert to base64 */
1566                 if( ctrls[i]->ldctl_value.bv_len ) {
1567                         b64 = ber_memalloc( sizeof(struct berval) );
1568                         
1569                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1570                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1571                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1572
1573                         b64->bv_len = lutil_b64_ntop(
1574                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1575                                 b64->bv_val, b64->bv_len );
1576                 }
1577
1578                 if( b64 ) {
1579                         len += 1 + b64->bv_len;
1580                 }
1581
1582                 str = malloc( len + 1 );
1583                 strcpy( str, ctrls[i]->ldctl_oid );
1584                 strcat( str, ctrls[i]->ldctl_iscritical
1585                         ? " true" : " false" );
1586
1587                 if( b64 ) {
1588                         strcat(str, " ");
1589                         strcat(str, b64->bv_val );
1590                 }
1591
1592                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1593                         "control", str, len );
1594
1595                 free( str );
1596                 ber_bvfree( b64 );
1597         }
1598 }
1599
1600 static int
1601 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1602 {
1603         char    *ldif;
1604
1605         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1606                 return( -1 );
1607         }
1608
1609         fputs( ldif, stdout );
1610         ber_memfree( ldif );
1611
1612         return( 0 );
1613 }