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