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