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