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