]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
add limits to entries count for paged results
[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 /* LDAP_CONTROL_PAGEDRESULTS */
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 "             [!]manageDSAit   (alternate form, see -M)\n"
84 "             [!]noop\n"
85 "  -f file    read operations from `file'\n"
86 "  -h host    LDAP server\n"
87 "  -H URI     LDAP Uniform Resource Indentifier(s)\n"
88 "  -I         use SASL Interactive mode\n"
89 "  -k         use Kerberos authentication\n"
90 "  -K         like -k, but do only step 1 of the Kerberos bind\n"
91 "  -M         enable Manage DSA IT control (-MM to make critical)\n"
92 "  -n         show what would be done but don't actually search\n"
93 "  -O props   SASL security properties\n"
94 "  -p port    port on LDAP server\n"
95 "  -P version procotol version (default: 3)\n"
96 "  -Q         use SASL Quiet mode\n"
97 "  -R realm   SASL realm\n"
98 "  -U authcid SASL authentication identity\n"
99 "  -v         run in verbose mode (diagnostics to standard output)\n"
100 "  -w passwd  bind passwd (for simple authentication)\n"
101 "  -W         prompt for bind passwd\n"
102 "  -x         Simple authentication\n"
103 "  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
104 "  -y file    Read passwd from file\n"
105 "  -Y mech    SASL mechanism\n"
106 "  -Z         Start TLS request (-ZZ to require successful response)\n"
107 , s, def_urlpre, def_tmpdir );
108
109         exit( EXIT_FAILURE );
110 }
111
112 static void print_entry LDAP_P((
113         LDAP    *ld,
114         LDAPMessage     *entry,
115         int             attrsonly));
116
117 static void print_reference(
118         LDAP *ld,
119         LDAPMessage *reference );
120
121 static void print_extended(
122         LDAP *ld,
123         LDAPMessage *extended );
124
125 static void print_partial(
126         LDAP *ld,
127         LDAPMessage *partial );
128
129 static int print_result(
130         LDAP *ld,
131         LDAPMessage *result,
132         int search );
133
134 static void print_ctrls(
135         LDAPControl **ctrls );
136
137 static int write_ldif LDAP_P((
138         int type,
139         char *name,
140         char *value,
141         ber_len_t vallen ));
142
143 static int dosearch LDAP_P((
144         LDAP    *ld,
145         char    *base,
146         int             scope,
147         char    *filtpatt,
148         char    *value,
149         char    **attrs,
150         int             attrsonly,
151         LDAPControl **sctrls,
152         LDAPControl **cctrls,
153         struct timeval *timeout,
154         int     sizelimit ));
155
156 #ifdef LDAP_CONTROL_PAGEDRESULTS
157 static int parse_page_control(
158         LDAP *ld,
159         LDAPMessage *result,
160         struct berval *cookie );
161 #endif /* LDAP_CONTROL_PAGEDRESULTS */
162
163 static char *tmpdir = NULL;
164 static char *urlpre = NULL;
165 static char *prog = NULL;
166 static char     *binddn = NULL;
167 static struct berval passwd = { 0, NULL };
168 static char     *base = NULL;
169 static char     *ldaphost = NULL;
170 static char *ldapuri = NULL;
171 static int      ldapport = 0;
172 #ifdef HAVE_CYRUS_SASL
173 static unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
174 static char     *sasl_realm = NULL;
175 static char     *sasl_authc_id = NULL;
176 static char     *sasl_authz_id = NULL;
177 static char     *sasl_mech = NULL;
178 static char     *sasl_secprops = NULL;
179 #endif
180 static int      use_tls = 0;
181 static char     *sortattr = NULL;
182 static int      verbose, not, includeufn, vals2tmp, ldif;
183 #ifdef LDAP_CONTROL_PAGEDRESULTS
184 static int pageSize = 0;
185 static ber_int_t searchControlSize = 0;
186 static ber_int_t entriesLeft = 0;
187 static ber_int_t morePagedResults = 1;
188 static struct berval cookie = { 0, NULL };
189 static int npagedresponses;
190 static int npagedentries;
191 static int npagedreferences;
192 static int npagedextended;
193 static int npagedpartial;
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   *bvalp = NULL;
221         char    *vrFilter  = NULL, *control = NULL, *cvalue;
222         char    *pw_file = NULL;
223 #ifdef LDAP_CONTROL_PAGEDRESULTS
224         BerElement      *pageber = NULL;
225         struct berval   *bvalptr = NULL;
226         int             num = 0, searchControlCrit = 0;
227 #endif /* LDAP_CONTROL_PAGEDRESULTS */
228
229
230         infile = NULL;
231         debug = verbose = not = vals2tmp = referrals =
232                 subentries = valuesReturnFilter =
233                 attrsonly = manageDSAit = noop = ldif = want_bindpw = 0;
234
235 #ifdef LDAP_CONTROL_PAGEDRESULTS
236         npagedresponses = npagedentries = npagedreferences =
237                 npagedextended = npagedpartial = 0;
238 #endif /* LDAP_CONTROL_PAGEDRESULTS */
239
240         prog = lutil_progname( "ldapsearch", argc, argv );
241
242         lutil_log_initialize(argc, argv);
243
244         deref = sizelimit = timelimit = version = -1;
245
246         scope = LDAP_SCOPE_SUBTREE;
247         authmethod = -1;
248
249         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
250            (def_tmpdir = getenv("TMP")) == NULL &&
251            (def_tmpdir = getenv("TEMP")) == NULL )
252         {
253                 def_tmpdir = LDAP_TMPDIR;
254         }
255
256         if ( !*def_tmpdir )
257                 def_tmpdir = LDAP_TMPDIR;
258
259         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
260
261         if( def_urlpre == NULL ) {
262                 perror( "malloc" );
263                 return EXIT_FAILURE;
264         }
265
266         sprintf( def_urlpre, "file:///%s/",
267                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
268
269         urlize( def_urlpre );
270
271         while (( i = getopt( argc, argv, "Aa:b:E:F:f:Ll:S:s:T:tuz:"
272                 "Cd:e:D:h:H:IkKMnO:p:P:QR:U:vw:WxX:y:Y:Z")) != EOF )
273         {
274         switch( i ) {
275         /* Search Options */
276         case 'a':       /* set alias deref option */
277                 if ( strcasecmp( optarg, "never" ) == 0 ) {
278                 deref = LDAP_DEREF_NEVER;
279                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
280                 deref = LDAP_DEREF_SEARCHING;
281                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
282                 deref = LDAP_DEREF_FINDING;
283                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
284                 deref = LDAP_DEREF_ALWAYS;
285                 } else {
286                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
287                 usage(prog);
288                 }
289                 break;
290         case 'A':       /* retrieve attribute names only -- no values */
291                 ++attrsonly;
292                 break;
293         case 'b': /* search base */
294                 base = strdup( optarg );
295                 break;
296         case 'E': /* search controls */
297                 if( version == LDAP_VERSION2 ) {
298                         fprintf( stderr, "%s: -E incompatible with LDAPv%d\n",
299                                 prog, version );
300                         return EXIT_FAILURE;
301                 }
302
303                 /* should be extended to support comma separated list of
304                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
305                  */
306
307                 crit = 0;
308                 cvalue = NULL;
309                 if( optarg[0] == '!' ) {
310                         crit = 1;
311                         optarg++;
312                 }
313
314                 control = strdup( optarg );
315                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
316                         *cvalue++ = '\0';
317                 }
318
319                 if ( strcasecmp( control, "mv" ) == 0 ) {
320                         /* ValuesReturnFilter control */
321                         if( valuesReturnFilter ) {
322                                 fprintf( stderr, "ValuesReturnFilter previously specified");
323                                 return EXIT_FAILURE;
324                         }
325                         valuesReturnFilter= 1 + crit;
326
327                         if ( cvalue == NULL ) {
328                                 fprintf( stderr,
329                                         "missing filter in ValuesReturnFilter control\n");
330                                 return EXIT_FAILURE;
331                         }
332
333                         vrFilter = cvalue;
334                         version = LDAP_VERSION3;
335                         break;
336
337 #ifdef LDAP_CONTROL_PAGEDRESULTS
338                 } else if ( strcasecmp( control, "pr" ) == 0 ) {
339                         /* PagedResults control */
340                         if ( pageSize != 0 ) {
341                                 fprintf( stderr, "PagedResultsControl previously specified" );
342                                 return EXIT_FAILURE;
343                         }
344                         
345                         num = sscanf( cvalue, "%d", &pageSize );
346                         if ( num != 1 ) {
347                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", cvalue);
348                                 return EXIT_FAILURE;
349
350                         }
351                         searchControlSize = (ber_int_t)pageSize;
352                         searchControlCrit = crit;
353                         break;
354 #endif /* LDAP_CONTROL_PAGEDRESULTS */
355
356 #ifdef LDAP_CONTROL_SUBENTRIES
357                 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
358                         if( subentries ) {
359                                 fprintf( stderr, "subentries control previously specified");
360                                 return EXIT_FAILURE;
361                         }
362                         if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
363                                 subentries = 2;
364                         } else if ( strcasecmp( cvalue, "false") == 0 ) {
365                                 subentries = 1;
366                         } else {
367                                 fprintf( stderr,
368                                         "subentries control value \"%s\" invalid\n");
369                                 return EXIT_FAILURE;
370                         }
371                         if( crit ) subentries *= -1;
372 #endif
373
374                 } else {
375                         fprintf( stderr, "Invalid control name: %s\n", control );
376                         usage(prog);
377                         return EXIT_FAILURE;
378                 }
379         case 'f':       /* input file */
380                 if( infile != NULL ) {
381                         fprintf( stderr, "%s: -f previously specified\n", prog );
382                         return EXIT_FAILURE;
383                 }
384                 infile = strdup( optarg );
385                 break;
386         case 'F':       /* uri prefix */
387                 if( urlpre ) free( urlpre );
388                 urlpre = strdup( optarg );
389                 break;
390         case 'l':       /* time limit */
391                 timelimit = atoi( optarg );
392                 if( timelimit < 0 ) {
393                         fprintf( stderr, "%s: invalid timelimit (%d) specified\n",
394                                 prog, timelimit );
395                         return EXIT_FAILURE;
396                 }
397                 break;
398         case 'L':       /* print entries in LDIF format */
399                 ++ldif;
400                 break;
401         case 's':       /* search scope */
402                 if ( strcasecmp( optarg, "base" ) == 0 ) {
403                 scope = LDAP_SCOPE_BASE;
404                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
405                 scope = LDAP_SCOPE_ONELEVEL;
406                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
407                 scope = LDAP_SCOPE_SUBTREE;
408                 } else {
409                 fprintf( stderr, "scope should be base, one, or sub\n" );
410                 usage(prog);
411                 }
412                 break;
413         case 'S':       /* sort attribute */
414                 sortattr = strdup( optarg );
415                 break;
416         case 'u':       /* include UFN */
417                 ++includeufn;
418                 break;
419         case 't':       /* write attribute values to TMPDIR files */
420                 ++vals2tmp;
421                 break;
422         case 'T':       /* tmpdir */
423                 if( tmpdir ) free( tmpdir );
424                 tmpdir = strdup( optarg );
425                 break;
426         case 'z':       /* size limit */
427                 sizelimit = atoi( optarg );
428                 break;
429
430         /* Common Options */
431         case 'C':
432                 referrals++;
433                 break;
434         case 'd':
435             debug |= atoi( optarg );
436             break;
437         case 'D':       /* bind DN */
438                 if( binddn != NULL ) {
439                         fprintf( stderr, "%s: -D previously specified\n", prog );
440                         return EXIT_FAILURE;
441                 }
442             binddn = strdup( optarg );
443             break;
444         case 'e': /* general controls */
445                 if( version == LDAP_VERSION2 ) {
446                         fprintf( stderr, "%s: -e incompatible with LDAPv%d\n",
447                                 prog, version );
448                         return EXIT_FAILURE;
449                 }
450
451                 /* should be extended to support comma separated list of
452                  *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
453                  */
454
455                 crit = 0;
456                 cvalue = NULL;
457                 if( optarg[0] == '!' ) {
458                         crit = 1;
459                         optarg++;
460                 }
461
462                 control = strdup( optarg );
463                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
464                         *cvalue++ = '\0';
465                 }
466
467                 if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
468                         if( manageDSAit ) {
469                                 fprintf( stderr, "manageDSAit control previously specified");
470                                 return EXIT_FAILURE;
471                         }
472                         if( cvalue != NULL ) {
473                                 fprintf( stderr, "manageDSAit: no control value expected" );
474                                 usage(prog);
475                                 return EXIT_FAILURE;
476                         }
477
478                         manageDSAit = 1 + crit;
479                         free( control );
480                         break;
481                         
482                 } else if ( strcasecmp( control, "noop" ) == 0 ) {
483                         if( noop ) {
484                                 fprintf( stderr, "noop control previously specified");
485                                 return EXIT_FAILURE;
486                         }
487                         if( cvalue != NULL ) {
488                                 fprintf( stderr, "noop: no control value expected" );
489                                 usage(prog);
490                                 return EXIT_FAILURE;
491                         }
492
493                         noop = 1 + crit;
494                         free( control );
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 || valuesReturnFilter || pageSize ) {
1030                 int critical = 0;
1031 #else /* !LDAP_CONTROL_PAGEDRESULTS */
1032         if ( manageDSAit || noop || valuesReturnFilter ) {
1033 #endif /* !LDAP_CONTROL_PAGEDRESULTS */
1034                 int err;
1035                 int i=0;
1036                 LDAPControl c1,c2,c3,c4,c5;
1037                 LDAPControl *ctrls[6];
1038                 
1039                 if ( manageDSAit ) {
1040                         ctrls[i++]=&c1;
1041                         ctrls[i] = NULL;
1042
1043                         c1.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1044                         c1.ldctl_value.bv_val = NULL;
1045                         c1.ldctl_value.bv_len = 0;
1046                         c1.ldctl_iscritical = manageDSAit > 1;
1047 #ifdef LDAP_CONTROL_PAGEDRESULTS
1048                         if ( c1.ldctl_iscritical ) critical = 1;
1049 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1050                 }
1051
1052                 if ( noop ) {
1053                         ctrls[i++] = &c2;
1054                         ctrls[i] = NULL;
1055
1056                         c2.ldctl_oid = LDAP_CONTROL_NOOP;
1057                         c2.ldctl_value.bv_val = NULL;
1058                         c2.ldctl_value.bv_len = 0;
1059                         c2.ldctl_iscritical = noop > 1;
1060 #ifdef LDAP_CONTROL_PAGEDRESULTS
1061                         if ( c2.ldctl_iscritical ) critical = 1;
1062 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1063                 }
1064
1065 #ifdef LDAP_CONTROL_SUBENTRIES
1066                 if ( subentries ) {
1067                         ctrls[i++]=&c3;
1068                         ctrls[i] = NULL;
1069
1070                         c3.ldctl_oid = LDAP_CONTROL_SUBENTRIES;
1071                         c3.ldctl_iscritical = subentries < 1;
1072 #ifdef LDAP_CONTROL_PAGEDRESULTS
1073                         if ( c3.ldctl_iscritical ) critical = 1;
1074 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1075                     
1076                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1077                                 return EXIT_FAILURE;
1078                         }
1079
1080                         err = ber_printf( ber, "{b}", abs(subentries) == 1 ? 0 : 1 );
1081                 if ( err == LBER_ERROR ) {
1082                                 ber_free( ber, 1 );
1083                                 fprintf( stderr, "Subentries control encoding error!\n" );
1084                                 return EXIT_FAILURE;
1085                         }
1086
1087                         if ( ber_flatten( ber, &bvalp ) == LBER_ERROR ) {
1088                                 return EXIT_FAILURE;
1089                         }
1090
1091                         c3.ldctl_value=(*bvalp);
1092                 }
1093 #endif
1094
1095                 if ( valuesReturnFilter ) {
1096                         ctrls[i++]=&c4;
1097                         ctrls[i] = NULL;
1098
1099                         c4.ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
1100                         c4.ldctl_iscritical = valuesReturnFilter > 1;
1101 #ifdef LDAP_CONTROL_PAGEDRESULTS
1102                         if ( c4.ldctl_iscritical ) critical = 1;
1103 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1104                     
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, &bvalp ) == LBER_ERROR ) {
1116                                 return EXIT_FAILURE;
1117                         }
1118
1119                         c4.ldctl_value=(*bvalp);
1120                 }
1121
1122 #ifdef LDAP_CONTROL_PAGEDRESULTS
1123                 if ( pageSize ) {
1124                         if (( pageber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1125                                 return EXIT_FAILURE;
1126                         }
1127
1128                         ber_printf( pageber, "{iO}", searchControlSize, &cookie );
1129                         if ( ber_flatten( pageber, &bvalptr ) == LBER_ERROR) {
1130                                 return EXIT_FAILURE;
1131                         }
1132                         
1133                         ctrls[i++]=&c5;
1134                         ctrls[i] = NULL;
1135
1136                         c5.ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1137                         c5.ldctl_value = ( *bvalptr );
1138                         c5.ldctl_iscritical = searchControlCrit;
1139                         if ( c5.ldctl_iscritical ) critical = 1;
1140                 }
1141 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1142
1143                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1144
1145                 ber_bvfree(bvalp);
1146                 ber_free( ber, 1 );
1147 #ifdef LDAP_CONTROL_PAGEDRESULTS
1148                 ber_free( pageber, 1 );
1149                 ber_bvfree( bvalptr );
1150 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1151
1152 #ifdef LDAP_CONTROL_PAGEDRESULTS
1153                 if( err != LDAP_OPT_SUCCESS ) {
1154                         if ( critical ) {
1155                                 fprintf( stderr, "Could not set controls\n");
1156                                 return EXIT_FAILURE;
1157                         } else {
1158                                 fprintf( stderr, "Could not set critical controls\n" );
1159                         }
1160                 }
1161 #else /* !LDAP_CONTROL_PAGEDRESULTS */
1162                 if( err != LDAP_OPT_SUCCESS ) {
1163                         fprintf( stderr, "Could not set %scontrols\n",
1164                                 (c1.ldctl_iscritical || c2.ldctl_iscritical)
1165                                 ? "critical " : "" );
1166                         if( c1.ldctl_iscritical && c2.ldctl_iscritical ) {
1167                                 return EXIT_FAILURE;
1168                         }
1169                 }
1170 #endif /* !LDAP_CONTROL_PAGEDRESULTS */
1171         }
1172         
1173         if ( verbose ) {
1174                 fprintf( stderr, "filter%s: %s\nrequesting: ",
1175                         infile != NULL ? " pattern" : "",
1176                         filtpattern );
1177
1178                 if ( attrs == NULL ) {
1179                         fprintf( stderr, "ALL" );
1180                 } else {
1181                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1182                                 fprintf( stderr, "%s ", attrs[ i ] );
1183                         }
1184                 }
1185                 fprintf( stderr, "\n" );
1186         }
1187
1188         if ( ldif == 0 ) {
1189                 printf( "# extended LDIF\n" );
1190         } else if ( ldif < 3 ) {
1191                 printf( "version: %d\n\n", 1 );
1192         }
1193
1194         if (ldif < 2 ) {
1195                 printf( "#\n"
1196                         "# LDAPv%d\n"
1197                         "# base <%s> with scope %s\n"
1198                         "# filter%s: %s\n"
1199                         "# requesting: ",
1200                         version,
1201                         base, (scope == LDAP_SCOPE_BASE) ? "base"
1202                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
1203                         infile != NULL ? " pattern" : "",
1204                         filtpattern );
1205
1206                 if ( attrs == NULL ) {
1207                         printf( "ALL" );
1208                 } else {
1209                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1210                                 printf( "%s ", attrs[ i ] );
1211                         }
1212                 }
1213
1214                 if ( manageDSAit ) {
1215                         printf("\n# with manageDSAit %scontrol",
1216                                 manageDSAit > 1 ? "critical " : "" );
1217                 }
1218                 if ( noop ) {
1219                         printf("\n# with noop %scontrol",
1220                                 noop > 1 ? "critical " : "" );
1221                 }
1222                 if ( subentries ) {
1223                         printf("\n# with subentries %scontrol: %s",
1224                                 subentries < 0 ? "critical " : "",
1225                                 abs(subentries) == 1 ? "false" : "true" );
1226                 }
1227                 if ( valuesReturnFilter ) {
1228                         printf("\n# with valuesReturnFilter %scontrol: %s",
1229                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
1230                 }
1231                 if ( pageSize ) {
1232                         printf("\n# with pagedResults %scontrol: size=%d",
1233                                 searchControlCrit ? "critical " : "", 
1234                                 searchControlSize );
1235                 }
1236
1237                 printf( "\n#\n\n" );
1238         }
1239
1240         if ( infile == NULL ) {
1241                 rc = dosearch( ld, base, scope, NULL, filtpattern,
1242                         attrs, attrsonly, NULL, NULL, NULL, -1 );
1243
1244         } else {
1245                 rc = 0;
1246                 first = 1;
1247                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
1248                         line[ strlen( line ) - 1 ] = '\0';
1249                         if ( !first ) {
1250                                 putchar( '\n' );
1251                         } else {
1252                                 first = 0;
1253                         }
1254                         rc = dosearch( ld, base, scope, filtpattern, line,
1255                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1256                 }
1257                 if ( fp != stdin ) {
1258                         fclose( fp );
1259                 }
1260         }
1261
1262 #ifdef LDAP_CONTROL_PAGEDRESULTS
1263         if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) { 
1264                 char    buf[6];
1265                 int     i, moreEntries, tmpSize;
1266
1267                 /* Loop to get the next pages when 
1268                  * enter is pressed on the terminal.
1269                  */
1270                 if ( entriesLeft > 0 ) {
1271                         printf( "Estimate entries: %d\n", entriesLeft );
1272                 }
1273                 printf( "Press [size] Enter for the next {%d|size} entries.\n",
1274                         (int)searchControlSize ); 
1275                 i = 0;
1276                 moreEntries = getchar();
1277                 while ( moreEntries != EOF && moreEntries != '\n' ) { 
1278                         if ( i < sizeof(buf) - 1 ) {
1279                                 buf[i] = moreEntries;
1280                                 i++;
1281                         }
1282                         moreEntries = getchar();
1283                 }
1284                 buf[i] = '\0';
1285
1286                 if ( i > 0 && isdigit( buf[0] ) ) {
1287                         num = sscanf( buf, "%d", &tmpSize );
1288                         if ( num != 1 ) {
1289                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
1290                                 return EXIT_FAILURE;
1291
1292                         }
1293                         searchControlSize = (ber_int_t)tmpSize;
1294                 }
1295
1296                 goto getNextPage;       
1297         }
1298 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1299
1300         ldap_unbind( ld );
1301         return( rc );
1302 }
1303
1304
1305 static int dosearch(
1306         LDAP    *ld,
1307         char    *base,
1308         int             scope,
1309         char    *filtpatt,
1310         char    *value,
1311         char    **attrs,
1312         int             attrsonly,
1313         LDAPControl **sctrls,
1314         LDAPControl **cctrls,
1315         struct timeval *timeout,
1316         int sizelimit )
1317 {
1318         char                    *filter;
1319         int                     rc;
1320         int                     nresponses;
1321         int                     nentries;
1322         int                     nreferences;
1323         int                     nextended;
1324         int                     npartial;
1325         LDAPMessage             *res, *msg;
1326         ber_int_t       msgid;
1327
1328         if( filtpatt != NULL ) {
1329                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1330                 if( filter == NULL ) {
1331                         perror( "malloc" );
1332                         return EXIT_FAILURE;
1333                 }
1334
1335                 sprintf( filter, filtpatt, value );
1336
1337                 if ( verbose ) {
1338                         fprintf( stderr, "filter: %s\n", filter );
1339                 }
1340
1341                 if( ldif < 2 ) {
1342                         printf( "#\n# filter: %s\n#\n", filter );
1343                 }
1344
1345         } else {
1346                 filter = value;
1347         }
1348
1349         if ( not ) {
1350                 return LDAP_SUCCESS;
1351         }
1352
1353         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1354                 sctrls, cctrls, timeout, sizelimit, &msgid );
1355
1356         if ( filtpatt != NULL ) {
1357                 free( filter );
1358         }
1359
1360         if( rc != LDAP_SUCCESS ) {
1361                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1362                         prog, ldap_err2string( rc ), rc );
1363                 return( rc );
1364         }
1365
1366         nresponses = nentries = nreferences = nextended = npartial = 0;
1367
1368         res = NULL;
1369
1370         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1371                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1372                 NULL, &res )) > 0 )
1373         {
1374                 if( sortattr ) {
1375                         (void) ldap_sort_entries( ld, &res,
1376                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1377                 }
1378
1379                 for ( msg = ldap_first_message( ld, res );
1380                         msg != NULL;
1381                         msg = ldap_next_message( ld, msg ) )
1382                 {
1383                         if( nresponses++ ) putchar('\n');
1384
1385                         switch( ldap_msgtype( msg ) ) {
1386                         case LDAP_RES_SEARCH_ENTRY:
1387                                 nentries++;
1388                                 print_entry( ld, msg, attrsonly );
1389                                 break;
1390
1391                         case LDAP_RES_SEARCH_REFERENCE:
1392                                 nreferences++;
1393                                 print_reference( ld, msg );
1394                                 break;
1395
1396                         case LDAP_RES_EXTENDED:
1397                                 nextended++;
1398                                 print_extended( ld, msg );
1399
1400                                 if( ldap_msgid( msg ) == 0 ) {
1401                                         /* unsolicited extended operation */
1402                                         goto done;
1403                                 }
1404                                 break;
1405
1406                         case LDAP_RES_EXTENDED_PARTIAL:
1407                                 npartial++;
1408                                 print_partial( ld, msg );
1409                                 break;
1410
1411                         case LDAP_RES_SEARCH_RESULT:
1412                                 rc = print_result( ld, msg, 1 );
1413 #ifdef LDAP_CONTROL_PAGEDRESULTS
1414                                 if ( pageSize != 0 ) { 
1415                                         rc = parse_page_control( ld, msg, &cookie );
1416                                 }
1417 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1418                                 goto done;
1419                         }
1420                 }
1421
1422                 ldap_msgfree( res );
1423         }
1424
1425         if ( rc == -1 ) {
1426                 ldap_perror( ld, "ldap_result" );
1427                 return( rc );
1428         }
1429
1430 done:
1431 #ifdef LDAP_CONTROL_PAGEDRESULTS
1432         if ( pageSize == 0 ) { 
1433                 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         } else {
1441                 npagedresponses = npagedresponses + nresponses;
1442                 npagedentries = npagedentries + nentries;
1443                 npagedreferences = npagedreferences + nreferences;
1444                 npagedextended = npagedextended + nextended;
1445                 npagedpartial = npagedpartial + npartial;
1446                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1447                         printf( "\n# numResponses: %d\n", npagedresponses );
1448                         if( nentries ) printf( "# numEntries: %d\n", npagedentries );
1449                         if( nextended ) printf( "# numExtended: %d\n", npagedextended );
1450                         if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
1451                         if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
1452                 }
1453         }
1454 #else /* !LDAP_CONTROL_PAGEDRESULTS */
1455         if ( ldif < 2 ) {
1456                 printf( "\n# numResponses: %d\n", nresponses );
1457                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1458                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1459                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1460                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1461         }
1462 #endif /* LDAP_CONTROL_PAGEDRESULTS */
1463
1464         return( rc );
1465 }
1466
1467 #if 1
1468 /* This is the original version, the old way of doing things. */
1469 static void
1470 print_entry(
1471         LDAP    *ld,
1472         LDAPMessage     *entry,
1473         int             attrsonly)
1474 {
1475         char            *a, *dn, *ufn;
1476         char    tmpfname[ 256 ];
1477         char    url[ 256 ];
1478         int                     i, rc;
1479         BerElement              *ber = NULL;
1480         struct berval   **bvals;
1481         LDAPControl **ctrls = NULL;
1482         FILE            *tmpfp;
1483
1484         dn = ldap_get_dn( ld, entry );
1485         ufn = NULL;
1486
1487         if ( ldif < 2 ) {
1488                 ufn = ldap_dn2ufn( dn );
1489                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1490         }
1491         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1492
1493         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1494
1495         if( rc != LDAP_SUCCESS ) {
1496                 fprintf(stderr, "print_entry: %d\n", rc );
1497                 ldap_perror( ld, "ldap_get_entry_controls" );
1498                 exit( EXIT_FAILURE );
1499         }
1500
1501         if( ctrls ) {
1502                 print_ctrls( ctrls );
1503                 ldap_controls_free( ctrls );
1504         }
1505
1506         if ( includeufn ) {
1507                 if( ufn == NULL ) {
1508                         ufn = ldap_dn2ufn( dn );
1509                 }
1510                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1511         }
1512
1513         if( ufn != NULL ) ldap_memfree( ufn );
1514         ldap_memfree( dn );
1515
1516         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1517                 a = ldap_next_attribute( ld, entry, ber ) )
1518         {
1519                 if ( attrsonly ) {
1520                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1521
1522                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1523                         for ( i = 0; bvals[i] != NULL; i++ ) {
1524                                 if ( vals2tmp > 1 || ( vals2tmp
1525                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1526                                 {
1527                                         int tmpfd;
1528                                         /* write value to file */
1529                                         snprintf( tmpfname, sizeof tmpfname,
1530                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1531                                                 tmpdir, a );
1532                                         tmpfp = NULL;
1533
1534                                         tmpfd = mkstemp( tmpfname );
1535
1536                                         if ( tmpfd < 0  ) {
1537                                                 perror( tmpfname );
1538                                                 continue;
1539                                         }
1540
1541                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1542                                                 perror( tmpfname );
1543                                                 continue;
1544                                         }
1545
1546                                         if ( fwrite( bvals[ i ]->bv_val,
1547                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1548                                         {
1549                                                 perror( tmpfname );
1550                                                 fclose( tmpfp );
1551                                                 continue;
1552                                         }
1553
1554                                         fclose( tmpfp );
1555
1556                                         snprintf( url, sizeof url, "%s%s", urlpre,
1557                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1558
1559                                         urlize( url );
1560                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1561
1562                                 } else {
1563                                         write_ldif( LDIF_PUT_VALUE, a,
1564                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1565                                 }
1566                         }
1567                         ber_bvecfree( bvals );
1568                 }
1569         }
1570
1571         if( ber != NULL ) {
1572                 ber_free( ber, 0 );
1573         }
1574 }
1575 #else
1576 /* This is the proposed new way of doing things.
1577  * It is more * efficient, but the API is non-standard.
1578  */
1579 static void
1580 print_entry(
1581         LDAP    *ld,
1582         LDAPMessage     *entry,
1583         int             attrsonly)
1584 {
1585         char            *ufn = NULL;
1586         char    tmpfname[ 256 ];
1587         char    url[ 256 ];
1588         int                     i, rc;
1589         BerElement              *ber = NULL;
1590         struct berval           bv, *bvals, **bvp = &bvals;
1591         LDAPControl **ctrls = NULL;
1592         FILE            *tmpfp;
1593
1594         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1595
1596         if ( ldif < 2 ) {
1597                 ufn = ldap_dn2ufn( bv.bv_val );
1598                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1599         }
1600         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1601
1602         rc = ldap_int_get_controls( ber, &ctrls );
1603
1604         if( rc != LDAP_SUCCESS ) {
1605                 fprintf(stderr, "print_entry: %d\n", rc );
1606                 ldap_perror( ld, "ldap_get_entry_controls" );
1607                 exit( EXIT_FAILURE );
1608         }
1609
1610         if( ctrls ) {
1611                 print_ctrls( ctrls );
1612                 ldap_controls_free( ctrls );
1613         }
1614
1615         if ( includeufn ) {
1616                 if( ufn == NULL ) {
1617                         ufn = ldap_dn2ufn( bv.bv_val );
1618                 }
1619                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1620         }
1621
1622         if( ufn != NULL ) ldap_memfree( ufn );
1623
1624         if ( attrsonly ) bvp = NULL;
1625
1626         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ); rc == LDAP_SUCCESS;
1627                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1628         {
1629                 if (bv.bv_val == NULL) break;
1630
1631                 if ( attrsonly ) {
1632                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1633
1634                 } else {
1635                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1636                                 if ( vals2tmp > 1 || ( vals2tmp
1637                                         && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1638                                 {
1639                                         int tmpfd;
1640                                         /* write value to file */
1641                                         snprintf( tmpfname, sizeof tmpfname,
1642                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1643                                                 tmpdir, bv.bv_val );
1644                                         tmpfp = NULL;
1645
1646                                         tmpfd = mkstemp( tmpfname );
1647
1648                                         if ( tmpfd < 0  ) {
1649                                                 perror( tmpfname );
1650                                                 continue;
1651                                         }
1652
1653                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1654                                                 perror( tmpfname );
1655                                                 continue;
1656                                         }
1657
1658                                         if ( fwrite( bvals[ i ].bv_val,
1659                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1660                                         {
1661                                                 perror( tmpfname );
1662                                                 fclose( tmpfp );
1663                                                 continue;
1664                                         }
1665
1666                                         fclose( tmpfp );
1667
1668                                         snprintf( url, sizeof url, "%s%s", urlpre,
1669                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1670
1671                                         urlize( url );
1672                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1673
1674                                 } else {
1675                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1676                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1677                                 }
1678                         }
1679                         ber_memfree( bvals );
1680                 }
1681         }
1682
1683         if( ber != NULL ) {
1684                 ber_free( ber, 0 );
1685         }
1686 }
1687 #endif
1688
1689 static void print_reference(
1690         LDAP *ld,
1691         LDAPMessage *reference )
1692 {
1693         int rc;
1694         char **refs = NULL;
1695         LDAPControl **ctrls;
1696
1697         if( ldif < 2 ) {
1698                 printf("# search reference\n");
1699         }
1700
1701         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1702
1703         if( rc != LDAP_SUCCESS ) {
1704                 ldap_perror(ld, "ldap_parse_reference");
1705                 exit( EXIT_FAILURE );
1706         }
1707
1708         if( refs ) {
1709                 int i;
1710                 for( i=0; refs[i] != NULL; i++ ) {
1711                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1712                                 "ref", refs[i], strlen(refs[i]) );
1713                 }
1714                 ber_memvfree( (void **) refs );
1715         }
1716
1717         if( ctrls ) {
1718                 print_ctrls( ctrls );
1719                 ldap_controls_free( ctrls );
1720         }
1721 }
1722
1723 static void print_extended(
1724         LDAP *ld,
1725         LDAPMessage *extended )
1726 {
1727         int rc;
1728         char *retoid = NULL;
1729         struct berval *retdata = NULL;
1730
1731         if( ldif < 2 ) {
1732                 printf("# extended result response\n");
1733         }
1734
1735         rc = ldap_parse_extended_result( ld, extended,
1736                 &retoid, &retdata, 0 );
1737
1738         if( rc != LDAP_SUCCESS ) {
1739                 ldap_perror(ld, "ldap_parse_extended_result");
1740                 exit( EXIT_FAILURE );
1741         }
1742
1743         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1744                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1745         ber_memfree( retoid );
1746
1747         if(retdata) {
1748                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1749                         "data", retdata->bv_val, retdata->bv_len );
1750                 ber_bvfree( retdata );
1751         }
1752
1753         print_result( ld, extended, 0 );
1754 }
1755
1756 static void print_partial(
1757         LDAP *ld,
1758         LDAPMessage *partial )
1759 {
1760         int rc;
1761         char *retoid = NULL;
1762         struct berval *retdata = NULL;
1763         LDAPControl **ctrls = NULL;
1764
1765         if( ldif < 2 ) {
1766                 printf("# extended partial response\n");
1767         }
1768
1769         rc = ldap_parse_extended_partial( ld, partial,
1770                 &retoid, &retdata, &ctrls, 0 );
1771
1772         if( rc != LDAP_SUCCESS ) {
1773                 ldap_perror(ld, "ldap_parse_extended_partial");
1774                 exit( EXIT_FAILURE );
1775         }
1776
1777         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1778                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1779
1780         ber_memfree( retoid );
1781
1782         if( retdata ) {
1783                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1784                         "data", 
1785                         retdata->bv_val, retdata->bv_len );
1786
1787                 ber_bvfree( retdata );
1788         }
1789
1790         if( ctrls ) {
1791                 print_ctrls( ctrls );
1792                 ldap_controls_free( ctrls );
1793         }
1794 }
1795
1796 static int print_result(
1797         LDAP *ld,
1798         LDAPMessage *result, int search )
1799 {
1800         int rc;
1801         int err;
1802         char *matcheddn = NULL;
1803         char *text = NULL;
1804         char **refs = NULL;
1805         LDAPControl **ctrls = NULL;
1806
1807         if( search ) {
1808                 if ( ldif < 2 ) {
1809                         printf("# search result\n");
1810                 }
1811                 if ( ldif < 1 ) {
1812                         printf("%s: %d\n", "search", ldap_msgid(result) );
1813                 }
1814         }
1815
1816         rc = ldap_parse_result( ld, result,
1817                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1818
1819         if( rc != LDAP_SUCCESS ) {
1820                 ldap_perror(ld, "ldap_parse_result");
1821                 exit( EXIT_FAILURE );
1822         }
1823
1824
1825         if( !ldif ) {
1826                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1827
1828         } else if ( err != LDAP_SUCCESS ) {
1829                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1830         }
1831
1832         if( matcheddn && *matcheddn ) {
1833                 if( !ldif ) {
1834                         write_ldif( LDIF_PUT_VALUE,
1835                                 "matchedDN", matcheddn, strlen(matcheddn) );
1836                 } else {
1837                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1838                 }
1839
1840                 ber_memfree( matcheddn );
1841         }
1842
1843         if( text && *text ) {
1844                 if( !ldif ) {
1845                         write_ldif( LDIF_PUT_TEXT, "text",
1846                                 text, strlen(text) );
1847                 } else {
1848                         fprintf( stderr, "Additional information: %s\n", text );
1849                 }
1850
1851                 ber_memfree( text );
1852         }
1853
1854         if( refs ) {
1855                 int i;
1856                 for( i=0; refs[i] != NULL; i++ ) {
1857                         if( !ldif ) {
1858                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1859                         } else {
1860                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1861                         }
1862                 }
1863
1864                 ber_memvfree( (void **) refs );
1865         }
1866
1867         if( ctrls ) {
1868                 print_ctrls( ctrls );
1869                 ldap_controls_free( ctrls );
1870         }
1871
1872         return err;
1873 }
1874
1875 static void print_ctrls(
1876         LDAPControl **ctrls )
1877 {
1878         int i;
1879         for(i=0; ctrls[i] != NULL; i++ ) {
1880                 /* control: OID criticality base64value */
1881                 struct berval *b64 = NULL;
1882                 ber_len_t len;
1883                 char *str;
1884                         
1885                 len = strlen( ctrls[i]->ldctl_oid );
1886
1887                 /* add enough for space after OID and the critical value itself */
1888                 len += ctrls[i]->ldctl_iscritical
1889                         ? sizeof("true") : sizeof("false");
1890
1891                 /* convert to base64 */
1892                 if( ctrls[i]->ldctl_value.bv_len ) {
1893                         b64 = ber_memalloc( sizeof(struct berval) );
1894                         
1895                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1896                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1897                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1898
1899                         b64->bv_len = lutil_b64_ntop(
1900                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1901                                 b64->bv_val, b64->bv_len );
1902                 }
1903
1904                 if( b64 ) {
1905                         len += 1 + b64->bv_len;
1906                 }
1907
1908                 str = malloc( len + 1 );
1909                 strcpy( str, ctrls[i]->ldctl_oid );
1910                 strcat( str, ctrls[i]->ldctl_iscritical
1911                         ? " true" : " false" );
1912
1913                 if( b64 ) {
1914                         strcat(str, " ");
1915                         strcat(str, b64->bv_val );
1916                 }
1917
1918                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1919                         "control", str, len );
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 */
2007