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