]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Happy new year
[openldap] / clients / tools / ldapsearch.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2003 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         if ( manageDSAit || noop || subentries
530                         || valuesReturnFilter || pageSize
531 #ifdef LDAP_CLIENT_UPDATE
532                         || lcup
533 #endif /* LDAP_CLIENT_UPDATE */
534                         ) {
535                 int err;
536                 int i=0;
537                 LDAPControl c[3];
538
539 #ifdef LDAP_CONTROL_SUBENTRIES
540                 if ( subentries ) {
541                 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
542                                 return EXIT_FAILURE;
543                         }
544
545                         err = ber_printf( seber, "{b}", abs(subentries) == 1 ? 0 : 1 );
546                 if ( err == LBER_ERROR ) {
547                                 ber_free( seber, 1 );
548                                 fprintf( stderr, "Subentries control encoding error!\n" );
549                                 return EXIT_FAILURE;
550                         }
551
552                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == LBER_ERROR ) {
553                                 return EXIT_FAILURE;
554                         }
555
556                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
557                         c[i].ldctl_iscritical = subentries < 1;
558                         i++;
559                 }
560 #endif
561
562 #ifdef LDAP_CLIENT_UPDATE
563                 if ( lcup ) {
564                         if (( cuber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
565                                 return EXIT_FAILURE;
566                         }
567                         err = ber_printf( cuber, "{ei{sO}}", abs(lcup), lcup_cint,
568                                         LDAP_CLIENT_UPDATE_COOKIE, &lcup_cookie);
569                         if ( err == LBER_ERROR ) {
570                                 ber_free( cuber, 1 );
571                                 fprintf( stderr, "client update control encoding error!\n" );
572                                 return EXIT_FAILURE;
573                         }
574
575                         if ( ber_flatten( cuber, &cubvalp ) == LBER_ERROR ) {
576                                 return EXIT_FAILURE;
577                         }
578
579                         c[i].ldctl_oid = LDAP_CONTROL_CLIENT_UPDATE;
580                         c[i].ldctl_value=(*cubvalp);
581                         c[i].ldctl_iscritical = lcup < 0;
582                         i++;
583                 }
584 #endif
585
586                 if ( valuesReturnFilter ) {
587                 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
588                                 return EXIT_FAILURE;
589                         }
590
591                 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
592                                 ber_free( vrber, 1 );
593                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
594                                 return EXIT_FAILURE;
595                         }
596
597                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == LBER_ERROR ) {
598                                 return EXIT_FAILURE;
599                         }
600
601                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
602                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
603                         i++;
604                 }
605
606                 if ( pagedResults ) {
607                         if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
608                                 return EXIT_FAILURE;
609                         }
610
611                         ber_printf( prber, "{iO}", pageSize, &cookie );
612                         if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == LBER_ERROR ) {
613                                 return EXIT_FAILURE;
614                         }
615                         
616                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
617                         c[i].ldctl_iscritical = pagedResults > 1;
618                         i++;
619                 }
620
621                 tool_server_controls( ld, c, i );
622
623                 ber_free( seber, 1 );
624                 ber_free( vrber, 1 );
625                 ber_free( prber, 1 );
626         }
627         
628         if ( verbose ) {
629                 fprintf( stderr, "filter%s: %s\nrequesting: ",
630                         infile != NULL ? " pattern" : "",
631                         filtpattern );
632
633                 if ( attrs == NULL ) {
634                         fprintf( stderr, "ALL" );
635                 } else {
636                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
637                                 fprintf( stderr, "%s ", attrs[ i ] );
638                         }
639                 }
640                 fprintf( stderr, "\n" );
641         }
642
643         if ( ldif == 0 ) {
644                 printf( "# extended LDIF\n" );
645         } else if ( ldif < 3 ) {
646                 printf( "version: %d\n\n", 1 );
647         }
648
649         if (ldif < 2 ) {
650                 printf( "#\n"
651                         "# LDAPv%d\n"
652                         "# base <%s> with scope %s\n"
653                         "# filter%s: %s\n"
654                         "# requesting: ",
655                         version,
656                         base ? base : "", (scope == LDAP_SCOPE_BASE) ? "base"
657                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
658                         infile != NULL ? " pattern" : "",
659                         filtpattern );
660
661                 if ( attrs == NULL ) {
662                         printf( "ALL" );
663                 } else {
664                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
665                                 printf( "%s ", attrs[ i ] );
666                         }
667                 }
668
669                 if ( manageDSAit ) {
670                         printf("\n# with manageDSAit %scontrol",
671                                 manageDSAit > 1 ? "critical " : "" );
672                 }
673                 if ( noop ) {
674                         printf("\n# with noop %scontrol",
675                                 noop > 1 ? "critical " : "" );
676                 }
677                 if ( subentries ) {
678                         printf("\n# with subentries %scontrol: %s",
679                                 subentries < 0 ? "critical " : "",
680                                 abs(subentries) == 1 ? "false" : "true" );
681                 }
682                 if ( valuesReturnFilter ) {
683                         printf("\n# with valuesReturnFilter %scontrol: %s",
684                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
685                 }
686                 if ( pageSize ) {
687                         printf("\n# with pagedResults %scontrol: size=%d",
688                                 (pagedResults > 1) ? "critical " : "", 
689                                 pageSize );
690                 }
691
692                 printf( "\n#\n\n" );
693         }
694
695         if ( infile == NULL ) {
696                 rc = dosearch( ld, base, scope, NULL, filtpattern,
697                         attrs, attrsonly, NULL, NULL, NULL, -1 );
698
699         } else {
700                 rc = 0;
701                 first = 1;
702                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
703                         line[ strlen( line ) - 1 ] = '\0';
704                         if ( !first ) {
705                                 putchar( '\n' );
706                         } else {
707                                 first = 0;
708                         }
709                         rc = dosearch( ld, base, scope, filtpattern, line,
710                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
711                 }
712                 if ( fp != stdin ) {
713                         fclose( fp );
714                 }
715         }
716
717         if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) { 
718                 char    buf[6];
719                 int     i, moreEntries, tmpSize;
720
721                 /* Loop to get the next pages when 
722                  * enter is pressed on the terminal.
723                  */
724                 if ( entriesLeft > 0 ) {
725                         printf( "Estimate entries: %d\n", entriesLeft );
726                 }
727                 printf( "Press [size] Enter for the next {%d|size} entries.\n",
728                         (int)pageSize ); 
729                 i = 0;
730                 moreEntries = getchar();
731                 while ( moreEntries != EOF && moreEntries != '\n' ) { 
732                         if ( i < sizeof(buf) - 1 ) {
733                                 buf[i] = moreEntries;
734                                 i++;
735                         }
736                         moreEntries = getchar();
737                 }
738                 buf[i] = '\0';
739
740                 if ( i > 0 && isdigit( buf[0] ) ) {
741                         int num = sscanf( buf, "%d", &tmpSize );
742                         if ( num != 1 ) {
743                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
744                                 return EXIT_FAILURE;
745
746                         }
747                         pageSize = (ber_int_t)tmpSize;
748                 }
749
750                 goto getNextPage;       
751         }
752
753         ldap_unbind( ld );
754         return( rc );
755 }
756
757
758 static int dosearch(
759         LDAP    *ld,
760         char    *base,
761         int             scope,
762         char    *filtpatt,
763         char    *value,
764         char    **attrs,
765         int             attrsonly,
766         LDAPControl **sctrls,
767         LDAPControl **cctrls,
768         struct timeval *timeout,
769         int sizelimit )
770 {
771         char                    *filter;
772         int                     rc;
773         int                     nresponses;
774         int                     nentries;
775         int                     nreferences;
776         int                     nextended;
777         int                     npartial;
778         LDAPMessage             *res, *msg;
779         ber_int_t       msgid;
780
781         if( filtpatt != NULL ) {
782                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
783                 if( filter == NULL ) {
784                         perror( "malloc" );
785                         return EXIT_FAILURE;
786                 }
787
788                 sprintf( filter, filtpatt, value );
789
790                 if ( verbose ) {
791                         fprintf( stderr, "filter: %s\n", filter );
792                 }
793
794                 if( ldif < 2 ) {
795                         printf( "#\n# filter: %s\n#\n", filter );
796                 }
797
798         } else {
799                 filter = value;
800         }
801
802         if ( not ) {
803                 return LDAP_SUCCESS;
804         }
805
806         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
807                 sctrls, cctrls, timeout, sizelimit, &msgid );
808
809         if ( filtpatt != NULL ) {
810                 free( filter );
811         }
812
813         if( rc != LDAP_SUCCESS ) {
814                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
815                         prog, ldap_err2string( rc ), rc );
816                 return( rc );
817         }
818
819         nresponses = nentries = nreferences = nextended = npartial = 0;
820
821         res = NULL;
822
823         while ((rc = ldap_result( ld, LDAP_RES_ANY,
824                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
825                 NULL, &res )) > 0 )
826         {
827                 if( sortattr ) {
828                         (void) ldap_sort_entries( ld, &res,
829                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
830                 }
831
832                 for ( msg = ldap_first_message( ld, res );
833                         msg != NULL;
834                         msg = ldap_next_message( ld, msg ) )
835                 {
836                         if( nresponses++ ) putchar('\n');
837
838                         switch( ldap_msgtype( msg ) ) {
839                         case LDAP_RES_SEARCH_ENTRY:
840                                 nentries++;
841                                 print_entry( ld, msg, attrsonly );
842                                 break;
843
844                         case LDAP_RES_SEARCH_REFERENCE:
845                                 nreferences++;
846                                 print_reference( ld, msg );
847                                 break;
848
849                         case LDAP_RES_EXTENDED:
850                                 nextended++;
851                                 print_extended( ld, msg );
852
853                                 if( ldap_msgid( msg ) == 0 ) {
854                                         /* unsolicited extended operation */
855                                         goto done;
856                                 }
857                                 break;
858
859                         case LDAP_RES_EXTENDED_PARTIAL:
860                                 npartial++;
861                                 print_partial( ld, msg );
862                                 break;
863
864                         case LDAP_RES_SEARCH_RESULT:
865                                 rc = print_result( ld, msg, 1 );
866                                 if ( pageSize != 0 ) { 
867                                         rc = parse_page_control( ld, msg, &cookie );
868                                 }
869                                 goto done;
870                         }
871 #ifdef LDAP_CLIENT_UPDATE
872                         if ( nresponses >= lcup_slimit ) {
873                                 ldap_abandon (ld, ldap_msgid(msg));
874                                 goto done;
875                         }
876 #endif
877
878                 }
879
880                 ldap_msgfree( res );
881         }
882
883         if ( rc == -1 ) {
884                 ldap_perror( ld, "ldap_result" );
885                 return( rc );
886         }
887
888 done:
889         if ( pageSize != 0 ) { 
890                 npagedresponses = npagedresponses + nresponses;
891                 npagedentries = npagedentries + nentries;
892                 npagedreferences = npagedreferences + nreferences;
893                 npagedextended = npagedextended + nextended;
894                 npagedpartial = npagedpartial + npartial;
895                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
896                         printf( "\n# numResponses: %d\n", npagedresponses );
897                         if( nentries ) printf( "# numEntries: %d\n", npagedentries );
898                         if( nextended ) printf( "# numExtended: %d\n", npagedextended );
899                         if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
900                         if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
901                 }
902         } else if ( ldif < 2 ) {
903                 printf( "\n# numResponses: %d\n", nresponses );
904                 if( nentries ) printf( "# numEntries: %d\n", nentries );
905                 if( nextended ) printf( "# numExtended: %d\n", nextended );
906                 if( npartial ) printf( "# numPartial: %d\n", npartial );
907                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
908         }
909
910         return( rc );
911 }
912
913 #if 1
914 /* This is the original version, the old way of doing things. */
915 static void
916 print_entry(
917         LDAP    *ld,
918         LDAPMessage     *entry,
919         int             attrsonly)
920 {
921         char            *a, *dn, *ufn;
922         char    tmpfname[ 256 ];
923         char    url[ 256 ];
924         int                     i, rc;
925         BerElement              *ber = NULL;
926         struct berval   **bvals;
927         LDAPControl **ctrls = NULL;
928         FILE            *tmpfp;
929
930         dn = ldap_get_dn( ld, entry );
931         ufn = NULL;
932
933         if ( ldif < 2 ) {
934                 ufn = ldap_dn2ufn( dn );
935                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
936         }
937         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
938
939         rc = ldap_get_entry_controls( ld, entry, &ctrls );
940
941         if( rc != LDAP_SUCCESS ) {
942                 fprintf(stderr, "print_entry: %d\n", rc );
943                 ldap_perror( ld, "ldap_get_entry_controls" );
944                 exit( EXIT_FAILURE );
945         }
946
947         if( ctrls ) {
948                 print_ctrls( ctrls );
949                 ldap_controls_free( ctrls );
950         }
951
952         if ( includeufn ) {
953                 if( ufn == NULL ) {
954                         ufn = ldap_dn2ufn( dn );
955                 }
956                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
957         }
958
959         if( ufn != NULL ) ldap_memfree( ufn );
960         ldap_memfree( dn );
961
962         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
963                 a = ldap_next_attribute( ld, entry, ber ) )
964         {
965                 if ( attrsonly ) {
966                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
967
968                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
969                         for ( i = 0; bvals[i] != NULL; i++ ) {
970                                 if ( vals2tmp > 1 || ( vals2tmp
971                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
972                                 {
973                                         int tmpfd;
974                                         /* write value to file */
975                                         snprintf( tmpfname, sizeof tmpfname,
976                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
977                                                 tmpdir, a );
978                                         tmpfp = NULL;
979
980                                         tmpfd = mkstemp( tmpfname );
981
982                                         if ( tmpfd < 0  ) {
983                                                 perror( tmpfname );
984                                                 continue;
985                                         }
986
987                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
988                                                 perror( tmpfname );
989                                                 continue;
990                                         }
991
992                                         if ( fwrite( bvals[ i ]->bv_val,
993                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
994                                         {
995                                                 perror( tmpfname );
996                                                 fclose( tmpfp );
997                                                 continue;
998                                         }
999
1000                                         fclose( tmpfp );
1001
1002                                         snprintf( url, sizeof url, "%s%s", urlpre,
1003                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1004
1005                                         urlize( url );
1006                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1007
1008                                 } else {
1009                                         write_ldif( LDIF_PUT_VALUE, a,
1010                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1011                                 }
1012                         }
1013                         ber_bvecfree( bvals );
1014                 }
1015                 ldap_memfree( a );
1016         }
1017
1018         if( ber != NULL ) {
1019                 ber_free( ber, 0 );
1020         }
1021 }
1022 #else
1023 /* This is the proposed new way of doing things.
1024  * It is more efficient, but the API is non-standard.
1025  */
1026 static void
1027 print_entry(
1028         LDAP    *ld,
1029         LDAPMessage     *entry,
1030         int             attrsonly)
1031 {
1032         char            *ufn = NULL;
1033         char    tmpfname[ 256 ];
1034         char    url[ 256 ];
1035         int                     i, rc;
1036         BerElement              *ber = NULL;
1037         struct berval           bv, *bvals, **bvp = &bvals;
1038         LDAPControl **ctrls = NULL;
1039         FILE            *tmpfp;
1040
1041         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1042
1043         if ( ldif < 2 ) {
1044                 ufn = ldap_dn2ufn( bv.bv_val );
1045                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1046         }
1047         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1048
1049         rc = ldap_int_get_controls( ber, &ctrls );
1050
1051         if( rc != LDAP_SUCCESS ) {
1052                 fprintf(stderr, "print_entry: %d\n", rc );
1053                 ldap_perror( ld, "ldap_get_entry_controls" );
1054                 exit( EXIT_FAILURE );
1055         }
1056
1057         if( ctrls ) {
1058                 print_ctrls( ctrls );
1059                 ldap_controls_free( ctrls );
1060         }
1061
1062         if ( includeufn ) {
1063                 if( ufn == NULL ) {
1064                         ufn = ldap_dn2ufn( bv.bv_val );
1065                 }
1066                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1067         }
1068
1069         if( ufn != NULL ) ldap_memfree( ufn );
1070
1071         if ( attrsonly ) bvp = NULL;
1072
1073         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1074                 rc == LDAP_SUCCESS;
1075                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1076         {
1077                 if (bv.bv_val == NULL) break;
1078
1079                 if ( attrsonly ) {
1080                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1081
1082                 } else {
1083                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1084                                 if ( vals2tmp > 1 || ( vals2tmp
1085                                         && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1086                                 {
1087                                         int tmpfd;
1088                                         /* write value to file */
1089                                         snprintf( tmpfname, sizeof tmpfname,
1090                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1091                                                 tmpdir, bv.bv_val );
1092                                         tmpfp = NULL;
1093
1094                                         tmpfd = mkstemp( tmpfname );
1095
1096                                         if ( tmpfd < 0  ) {
1097                                                 perror( tmpfname );
1098                                                 continue;
1099                                         }
1100
1101                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1102                                                 perror( tmpfname );
1103                                                 continue;
1104                                         }
1105
1106                                         if ( fwrite( bvals[ i ].bv_val,
1107                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1108                                         {
1109                                                 perror( tmpfname );
1110                                                 fclose( tmpfp );
1111                                                 continue;
1112                                         }
1113
1114                                         fclose( tmpfp );
1115
1116                                         snprintf( url, sizeof url, "%s%s", urlpre,
1117                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1118
1119                                         urlize( url );
1120                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1121
1122                                 } else {
1123                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1124                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1125                                 }
1126                         }
1127                         ber_memfree( bvals );
1128                 }
1129         }
1130
1131         if( ber != NULL ) {
1132                 ber_free( ber, 0 );
1133         }
1134 }
1135 #endif
1136
1137 static void print_reference(
1138         LDAP *ld,
1139         LDAPMessage *reference )
1140 {
1141         int rc;
1142         char **refs = NULL;
1143         LDAPControl **ctrls;
1144
1145         if( ldif < 2 ) {
1146                 printf("# search reference\n");
1147         }
1148
1149         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1150
1151         if( rc != LDAP_SUCCESS ) {
1152                 ldap_perror(ld, "ldap_parse_reference");
1153                 exit( EXIT_FAILURE );
1154         }
1155
1156         if( refs ) {
1157                 int i;
1158                 for( i=0; refs[i] != NULL; i++ ) {
1159                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1160                                 "ref", refs[i], strlen(refs[i]) );
1161                 }
1162                 ber_memvfree( (void **) refs );
1163         }
1164
1165         if( ctrls ) {
1166                 print_ctrls( ctrls );
1167                 ldap_controls_free( ctrls );
1168         }
1169 }
1170
1171 static void print_extended(
1172         LDAP *ld,
1173         LDAPMessage *extended )
1174 {
1175         int rc;
1176         char *retoid = NULL;
1177         struct berval *retdata = NULL;
1178
1179         if( ldif < 2 ) {
1180                 printf("# extended result response\n");
1181         }
1182
1183         rc = ldap_parse_extended_result( ld, extended,
1184                 &retoid, &retdata, 0 );
1185
1186         if( rc != LDAP_SUCCESS ) {
1187                 ldap_perror(ld, "ldap_parse_extended_result");
1188                 exit( EXIT_FAILURE );
1189         }
1190
1191         if ( ldif < 2 ) {
1192                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1193                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1194         }
1195         ber_memfree( retoid );
1196
1197         if(retdata) {
1198                 if ( ldif < 2 ) {
1199                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1200                                 "data", retdata->bv_val, retdata->bv_len );
1201                 }
1202                 ber_bvfree( retdata );
1203         }
1204
1205         print_result( ld, extended, 0 );
1206 }
1207
1208 static void print_partial(
1209         LDAP *ld,
1210         LDAPMessage *partial )
1211 {
1212         int rc;
1213         char *retoid = NULL;
1214         struct berval *retdata = NULL;
1215         LDAPControl **ctrls = NULL;
1216
1217         if( ldif < 2 ) {
1218                 printf("# extended partial response\n");
1219         }
1220
1221         rc = ldap_parse_extended_partial( ld, partial,
1222                 &retoid, &retdata, &ctrls, 0 );
1223
1224         if( rc != LDAP_SUCCESS ) {
1225                 ldap_perror(ld, "ldap_parse_extended_partial");
1226                 exit( EXIT_FAILURE );
1227         }
1228
1229         if ( ldif < 2 ) {
1230                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1231                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1232         }
1233
1234         ber_memfree( retoid );
1235
1236         if( retdata ) {
1237                 if ( ldif < 2 ) {
1238                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1239                                 "data", retdata->bv_val, retdata->bv_len );
1240                 }
1241
1242                 ber_bvfree( retdata );
1243         }
1244
1245         if( ctrls ) {
1246                 print_ctrls( ctrls );
1247                 ldap_controls_free( ctrls );
1248         }
1249 }
1250
1251 static int print_result(
1252         LDAP *ld,
1253         LDAPMessage *result, int search )
1254 {
1255         int rc;
1256         int err;
1257         char *matcheddn = NULL;
1258         char *text = NULL;
1259         char **refs = NULL;
1260         LDAPControl **ctrls = NULL;
1261
1262         if( search ) {
1263                 if ( ldif < 2 ) {
1264                         printf("# search result\n");
1265                 }
1266                 if ( ldif < 1 ) {
1267                         printf("%s: %d\n", "search", ldap_msgid(result) );
1268                 }
1269         }
1270
1271         rc = ldap_parse_result( ld, result,
1272                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1273
1274         if( rc != LDAP_SUCCESS ) {
1275                 ldap_perror(ld, "ldap_parse_result");
1276                 exit( EXIT_FAILURE );
1277         }
1278
1279
1280         if( !ldif ) {
1281                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1282
1283         } else if ( err != LDAP_SUCCESS ) {
1284                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1285         }
1286
1287         if( matcheddn && *matcheddn ) {
1288                 if( !ldif ) {
1289                         write_ldif( LDIF_PUT_VALUE,
1290                                 "matchedDN", matcheddn, strlen(matcheddn) );
1291                 } else {
1292                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1293                 }
1294
1295                 ber_memfree( matcheddn );
1296         }
1297
1298         if( text && *text ) {
1299                 if( !ldif ) {
1300                         write_ldif( LDIF_PUT_TEXT, "text",
1301                                 text, strlen(text) );
1302                 } else {
1303                         fprintf( stderr, "Additional information: %s\n", text );
1304                 }
1305
1306                 ber_memfree( text );
1307         }
1308
1309         if( refs ) {
1310                 int i;
1311                 for( i=0; refs[i] != NULL; i++ ) {
1312                         if( !ldif ) {
1313                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1314                         } else {
1315                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1316                         }
1317                 }
1318
1319                 ber_memvfree( (void **) refs );
1320         }
1321
1322         if( ctrls ) {
1323                 print_ctrls( ctrls );
1324                 ldap_controls_free( ctrls );
1325         }
1326
1327         return err;
1328 }
1329
1330 static void print_ctrls(
1331         LDAPControl **ctrls )
1332 {
1333         int i;
1334         for(i=0; ctrls[i] != NULL; i++ ) {
1335                 /* control: OID criticality base64value */
1336                 struct berval *b64 = NULL;
1337                 ber_len_t len;
1338                 char *str;
1339
1340                 len = ldif ? 2 : 0;
1341                 len += strlen( ctrls[i]->ldctl_oid );
1342
1343                 /* add enough for space after OID and the critical value itself */
1344                 len += ctrls[i]->ldctl_iscritical
1345                         ? sizeof("true") : sizeof("false");
1346
1347                 /* convert to base64 */
1348                 if( ctrls[i]->ldctl_value.bv_len ) {
1349                         b64 = ber_memalloc( sizeof(struct berval) );
1350                         
1351                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1352                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1353                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1354
1355                         b64->bv_len = lutil_b64_ntop(
1356                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1357                                 b64->bv_val, b64->bv_len );
1358                 }
1359
1360                 if( b64 ) {
1361                         len += 1 + b64->bv_len;
1362                 }
1363
1364                 str = malloc( len + 1 );
1365                 if ( ldif ) {
1366                         strcpy( str, ": " );
1367                 } else {
1368                         str[0] = '\0';
1369                 }
1370                 strcat( str, ctrls[i]->ldctl_oid );
1371                 strcat( str, ctrls[i]->ldctl_iscritical
1372                         ? " true" : " false" );
1373
1374                 if( b64 ) {
1375                         strcat(str, " ");
1376                         strcat(str, b64->bv_val );
1377                 }
1378
1379                 if ( ldif < 2 ) {
1380                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1381                                 "control", str, len );
1382                 }
1383
1384                 free( str );
1385                 ber_bvfree( b64 );
1386         }
1387 }
1388
1389 static int
1390 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1391 {
1392         char    *ldif;
1393
1394         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1395                 return( -1 );
1396         }
1397
1398         fputs( ldif, stdout );
1399         ber_memfree( ldif );
1400
1401         return( 0 );
1402 }
1403
1404
1405 static int 
1406 parse_page_control(
1407         LDAP *ld,
1408         LDAPMessage *result,
1409         struct berval *cookie )
1410 {
1411         int rc;
1412         int err;
1413         LDAPControl **ctrl = NULL;
1414         LDAPControl *ctrlp = NULL;
1415         BerElement *ber;
1416         ber_tag_t tag;
1417         struct berval servercookie = { 0, NULL };
1418
1419
1420         rc = ldap_parse_result( ld, result,
1421                 &err, NULL, NULL, NULL, &ctrl, 0 );
1422
1423         if( rc != LDAP_SUCCESS ) {
1424                 ldap_perror(ld, "ldap_parse_result");
1425                 exit( EXIT_FAILURE );
1426         }
1427
1428         if ( err != LDAP_SUCCESS ) {
1429                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1430         }
1431
1432         if( ctrl ) {
1433                 /* Parse the control value
1434                  * searchResult ::= SEQUENCE {
1435                  *              size    INTEGER (0..maxInt),
1436                  *                              -- result set size estimate from server - unused
1437                  *              cookie  OCTET STRING
1438                  */
1439                 ctrlp = *ctrl;
1440                 ber = ber_init( &ctrlp->ldctl_value );
1441                 if ( ber == NULL ) {
1442                         fprintf( stderr, "Internal error.\n" );
1443                         return EXIT_FAILURE;
1444                 }
1445
1446                 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1447                 ber_dupbv( cookie, &servercookie );
1448                 (void) ber_free( ber, 1 );
1449
1450                 if( tag == LBER_ERROR ) {
1451                         fprintf( stderr, "Paged results response control could not be decoded.\n" );
1452                         return EXIT_FAILURE;
1453                 }
1454
1455                 if( entriesLeft < 0 ) {
1456                         fprintf( stderr, "Invalid entries estimate in paged results response.\n" );
1457                         return EXIT_FAILURE;
1458                 }
1459
1460
1461                 ldap_controls_free( ctrl );
1462         } else {
1463                 morePagedResults = 0;
1464         }
1465
1466         return err;
1467 }