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