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