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