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