]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
a56631015fb6ce2897b0b36fae24ff3057e77770
[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                 if ( strcasecmp( optarg, "none" ) == 0 ) {
432                         timelimit = 0;
433                 } else {
434                         timelimit = atoi( optarg );
435                 }
436                 if( timelimit < 0 ) {
437                         fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
438                                 prog, timelimit );
439                         exit( EXIT_FAILURE );
440                 }
441                 break;
442         case 'L':       /* print entries in LDIF format */
443                 ++ldif;
444                 break;
445         case 's':       /* search scope */
446                 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
447                         scope = LDAP_SCOPE_BASE;
448                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
449                         scope = LDAP_SCOPE_ONELEVEL;
450 #ifdef LDAP_SCOPE_SUBORDINATE
451                 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
452                         || ( strcasecmp( optarg, "children" ) == 0 ))
453                 {
454                         scope = LDAP_SCOPE_SUBORDINATE;
455 #endif
456                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
457                         scope = LDAP_SCOPE_SUBTREE;
458                 } else {
459                         fprintf( stderr, _("scope should be base, one, or sub\n") );
460                         usage();
461                 }
462                 break;
463         case 'S':       /* sort attribute */
464                 sortattr = strdup( optarg );
465                 break;
466         case 't':       /* write attribute values to TMPDIR files */
467                 ++vals2tmp;
468                 break;
469         case 'T':       /* tmpdir */
470                 if( tmpdir ) free( tmpdir );
471                 tmpdir = strdup( optarg );
472                 break;
473         case 'u':       /* include UFN */
474                 ++includeufn;
475                 break;
476         case 'z':       /* size limit */
477                 if ( strcasecmp( optarg, "none" ) == 0 ) {
478                         sizelimit = 0;
479                 } else {
480                         sizelimit = atoi( optarg );
481                 }
482                 if( sizelimit < 0 ) {
483                         fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
484                                 prog, timelimit );
485                         exit( EXIT_FAILURE );
486                 }
487                 break;
488         default:
489                 return 0;
490         }
491         return 1;
492 }
493
494
495 static void
496 private_conn_setup( LDAP *ld )
497 {
498         if (deref != -1 &&
499                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
500                         != LDAP_OPT_SUCCESS )
501         {
502                 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
503                 exit( EXIT_FAILURE );
504         }
505         if (timelimit > 0 &&
506                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
507                         != LDAP_OPT_SUCCESS )
508         {
509                 fprintf( stderr,
510                         _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
511                 exit( EXIT_FAILURE );
512         }
513         if (sizelimit > 0 &&
514                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
515                         != LDAP_OPT_SUCCESS )
516         {
517                 fprintf( stderr,
518                         _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
519                 exit( EXIT_FAILURE );
520         }
521 }
522
523
524 int
525 main( int argc, char **argv )
526 {
527         char            *filtpattern, **attrs = NULL, line[BUFSIZ];
528         FILE            *fp = NULL;
529         int                     rc, i, first;
530         LDAP            *ld = NULL;
531         BerElement      *seber = NULL, *vrber = NULL, *prber = NULL;
532
533         BerElement      *syncber = NULL;
534         struct berval   *syncbvalp = NULL;
535
536         tool_init();
537
538 #ifdef LDAP_CONTROL_PAGEDRESULTS
539         npagedresponses = npagedentries = npagedreferences =
540                 npagedextended = npagedpartial = 0;
541 #endif
542
543         prog = lutil_progname( "ldapsearch", argc, argv );
544
545         lutil_log_initialize(argc, argv);
546
547         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
548            (def_tmpdir = getenv("TMP")) == NULL &&
549            (def_tmpdir = getenv("TEMP")) == NULL )
550         {
551                 def_tmpdir = LDAP_TMPDIR;
552         }
553
554         if ( !*def_tmpdir )
555                 def_tmpdir = LDAP_TMPDIR;
556
557         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
558
559         if( def_urlpre == NULL ) {
560                 perror( "malloc" );
561                 return EXIT_FAILURE;
562         }
563
564         sprintf( def_urlpre, "file:///%s/",
565                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
566
567         urlize( def_urlpre );
568
569         tool_args( argc, argv );
570
571         if (( argc - optind < 1 ) ||
572                 ( *argv[optind] != '(' /*')'*/ &&
573                 ( strchr( argv[optind], '=' ) == NULL ) ) )
574         {
575                 filtpattern = "(objectclass=*)";
576         } else {
577                 filtpattern = strdup( argv[optind++] );
578         }
579
580         if ( argv[optind] != NULL ) {
581                 attrs = &argv[optind];
582         }
583
584         if ( infile != NULL ) {
585                 if ( infile[0] == '-' && infile[1] == '\0' ) {
586                         fp = stdin;
587                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
588                         perror( infile );
589                         return EXIT_FAILURE;
590                 }
591         }
592
593         if ( tmpdir == NULL ) {
594                 tmpdir = def_tmpdir;
595
596                 if ( urlpre == NULL )
597                         urlpre = def_urlpre;
598         }
599
600         if( urlpre == NULL ) {
601                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
602
603                 if( urlpre == NULL ) {
604                         perror( "malloc" );
605                         return EXIT_FAILURE;
606                 }
607
608                 sprintf( urlpre, "file:///%s/",
609                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
610
611                 urlize( urlpre );
612         }
613
614         if ( debug )
615                 ldif_debug = debug;
616
617         ld = tool_conn_setup( 0, &private_conn_setup );
618
619         if ( pw_file || want_bindpw ) {
620                 if ( pw_file ) {
621                         rc = lutil_get_filed_password( pw_file, &passwd );
622                         if( rc ) return EXIT_FAILURE;
623                 } else {
624                         passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
625                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
626                 }
627         }
628
629         tool_bind( ld );
630
631 getNextPage:
632         if ( assertion || authzid || manageDSAit || noop
633 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
634                 || domainScope
635 #endif
636 #ifdef LDAP_CONTROL_PAGEDRESULTS
637                 || pageSize
638 #endif
639                 || ldapsync
640                 || subentries || valuesReturnFilter )
641         {
642                 int err;
643                 int i=0;
644                 LDAPControl c[6];
645
646 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
647         if ( domainScope ) {
648                 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
649                 c[i].ldctl_value.bv_val = NULL;
650                 c[i].ldctl_value.bv_len = 0;
651                 c[i].ldctl_iscritical = domainScope > 1;
652                 i++;
653         }
654 #endif
655
656 #ifdef LDAP_CONTROL_SUBENTRIES
657                 if ( subentries ) {
658                 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
659                                 return EXIT_FAILURE;
660                         }
661
662                         err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
663                 if ( err == -1 ) {
664                                 ber_free( seber, 1 );
665                                 fprintf( stderr, _("Subentries control encoding error!\n") );
666                                 return EXIT_FAILURE;
667                         }
668
669                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
670                                 return EXIT_FAILURE;
671                         }
672
673                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
674                         c[i].ldctl_iscritical = subentries < 1;
675                         i++;
676                 }
677 #endif
678
679                 if ( ldapsync ) {
680                         if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
681                                 return EXIT_FAILURE;
682                         }
683
684                         if ( sync_cookie.bv_len == 0 ) {
685                                 err = ber_printf( syncber, "{e}", abs(ldapsync) );
686                         } else {
687                                 err = ber_printf( syncber, "{eO}", abs(ldapsync),
688                                                         &sync_cookie );
689                         }
690
691                         if ( err == LBER_ERROR ) {
692                                 ber_free( syncber, 1 );
693                                 fprintf( stderr, _("ldap sync control encoding error!\n") );
694                                 return EXIT_FAILURE;
695                         }
696
697                         if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
698                                 return EXIT_FAILURE;
699                         }
700
701                         c[i].ldctl_oid = LDAP_CONTROL_SYNC;
702                         c[i].ldctl_value = (*syncbvalp);
703                         c[i].ldctl_iscritical = ldapsync < 0;
704                         i++;
705                 }
706
707                 if ( valuesReturnFilter ) {
708                 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
709                                 return EXIT_FAILURE;
710                         }
711
712                 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
713                                 ber_free( vrber, 1 );
714                                 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
715                                 return EXIT_FAILURE;
716                         }
717
718                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
719                                 return EXIT_FAILURE;
720                         }
721
722                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
723                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
724                         i++;
725                 }
726
727 #ifdef LDAP_CONTROL_PAGEDRESULTS
728                 if ( pagedResults ) {
729                         if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
730                                 return EXIT_FAILURE;
731                         }
732
733                         ber_printf( prber, "{iO}", pageSize, &cookie );
734                         if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
735                                 return EXIT_FAILURE;
736                         }
737                         
738                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
739                         c[i].ldctl_iscritical = pagedResults > 1;
740                         i++;
741                 }
742 #endif
743
744                 tool_server_controls( ld, c, i );
745
746 #ifdef LDAP_CONTROL_SUBENTRIES
747                 ber_free( seber, 1 );
748 #endif
749                 ber_free( vrber, 1 );
750 #ifdef LDAP_CONTROL_PAGEDRESULTS
751                 ber_free( prber, 1 );
752 #endif
753         }
754         
755         if ( verbose ) {
756                 fprintf( stderr, _("filter%s: %s\nrequesting: "),
757                         infile != NULL ? _(" pattern") : "",
758                         filtpattern );
759
760                 if ( attrs == NULL ) {
761                         fprintf( stderr, _("ALL") );
762                 } else {
763                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
764                                 fprintf( stderr, "%s ", attrs[ i ] );
765                         }
766                 }
767                 fprintf( stderr, "\n" );
768         }
769
770         if ( ldif == 0 ) {
771                 printf( _("# extended LDIF\n") );
772         } else if ( ldif < 3 ) {
773                 printf( _("version: %d\n\n"), 1 );
774         }
775
776         if (ldif < 2 ) {
777                 printf( "#\n" );
778                 printf(_("# LDAPv%d\n"), protocol);
779                 printf(_("# base <%s> with scope %s\n"),
780                         base ? base : "",
781                         ((scope == LDAP_SCOPE_BASE) ? "baseObject"
782                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
783 #ifdef LDAP_SCOPE_SUBORDINATE
784                                 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
785 #endif
786                                 : "subtree"
787 #ifdef LDAP_SCOPE_SUBORDINATE
788                                 )
789 #endif
790                                 )));
791                 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
792                        filtpattern);
793                 printf(_("# requesting: "));
794
795                 if ( attrs == NULL ) {
796                         printf( _("ALL") );
797                 } else {
798                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
799                                 printf( "%s ", attrs[ i ] );
800                         }
801                 }
802
803                 if ( manageDSAit ) {
804                         printf(_("\n# with manageDSAit %scontrol"),
805                                 manageDSAit > 1 ? _("critical ") : "" );
806                 }
807                 if ( noop ) {
808                         printf(_("\n# with noop %scontrol"),
809                                 noop > 1 ? _("critical ") : "" );
810                 }
811                 if ( subentries ) {
812                         printf(_("\n# with subentries %scontrol: %s"),
813                                 subentries < 0 ? _("critical ") : "",
814                                 abs(subentries) == 1 ? "false" : "true" );
815                 }
816                 if ( valuesReturnFilter ) {
817                         printf(_("\n# with valuesReturnFilter %scontrol: %s"),
818                                 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
819                 }
820 #ifdef LDAP_CONTROL_PAGEDRESULTS
821                 if ( pageSize ) {
822                         printf(_("\n# with pagedResults %scontrol: size=%d"),
823                                 (pagedResults > 1) ? _("critical ") : "", 
824                                 pageSize );
825                 }
826 #endif
827
828                 printf( _("\n#\n\n") );
829         }
830
831         if ( infile == NULL ) {
832                 rc = dosearch( ld, base, scope, NULL, filtpattern,
833                         attrs, attrsonly, NULL, NULL, NULL, -1 );
834
835         } else {
836                 rc = 0;
837                 first = 1;
838                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
839                         line[ strlen( line ) - 1 ] = '\0';
840                         if ( !first ) {
841                                 putchar( '\n' );
842                         } else {
843                                 first = 0;
844                         }
845                         rc = dosearch( ld, base, scope, filtpattern, line,
846                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
847                 }
848                 if ( fp != stdin ) {
849                         fclose( fp );
850                 }
851         }
852
853 #ifdef LDAP_CONTROL_PAGEDRESULTS
854         if ( ( rc == LDAP_SUCCESS ) &&  ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
855                 char    buf[6];
856                 int     i, moreEntries, tmpSize;
857
858                 /* Loop to get the next pages when 
859                  * enter is pressed on the terminal.
860                  */
861                 if ( pagePrompt != 0 ) {
862                         if ( entriesLeft > 0 ) {
863                                 printf( _("Estimate entries: %d\n"), entriesLeft );
864                         }
865                         printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
866                                 (int)pageSize );
867                         i = 0;
868                         moreEntries = getchar();
869                         while ( moreEntries != EOF && moreEntries != '\n' ) { 
870                                 if ( i < (int)sizeof(buf) - 1 ) {
871                                         buf[i] = moreEntries;
872                                         i++;
873                                 }
874                                 moreEntries = getchar();
875                         }
876                         buf[i] = '\0';
877
878                         if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
879                                 int num = sscanf( buf, "%d", &tmpSize );
880                                 if ( num != 1 ) {
881                                         fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
882                                         return EXIT_FAILURE;
883         
884                                 }
885                                 pageSize = (ber_int_t)tmpSize;
886                         }
887                 }
888
889                 goto getNextPage;       
890         }
891 #endif
892
893         ldap_unbind_ext( ld, NULL, NULL );
894 #ifdef HAVE_CYRUS_SASL
895         sasl_done();
896 #endif
897 #ifdef HAVE_TLS
898         ldap_pvt_tls_destroy();
899 #endif
900         return( rc );
901 }
902
903
904 static int dosearch(
905         LDAP    *ld,
906         char    *base,
907         int             scope,
908         char    *filtpatt,
909         char    *value,
910         char    **attrs,
911         int             attrsonly,
912         LDAPControl **sctrls,
913         LDAPControl **cctrls,
914         struct timeval *timeout,
915         int sizelimit )
916 {
917         char                    *filter;
918         int                     rc;
919         int                     nresponses;
920         int                     nentries;
921         int                     nreferences;
922         int                     nextended;
923         int                     npartial;
924         LDAPMessage             *res, *msg;
925         ber_int_t               msgid;
926         char                    *retoid = NULL;
927         struct berval           *retdata = NULL;
928         int                     nresponses_psearch = -1;
929         int                     cancel_msgid = -1;
930
931         if( filtpatt != NULL ) {
932                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
933                 if( filter == NULL ) {
934                         perror( "malloc" );
935                         return EXIT_FAILURE;
936                 }
937
938                 sprintf( filter, filtpatt, value );
939
940                 if ( verbose ) {
941                         fprintf( stderr, _("filter: %s\n"), filter );
942                 }
943
944                 if( ldif < 2 ) {
945                         printf( _("#\n# filter: %s\n#\n"), filter );
946                 }
947
948         } else {
949                 filter = value;
950         }
951
952         if ( not ) {
953                 return LDAP_SUCCESS;
954         }
955
956         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
957                 sctrls, cctrls, timeout, sizelimit, &msgid );
958
959         if ( filtpatt != NULL ) {
960                 free( filter );
961         }
962
963         if( rc != LDAP_SUCCESS ) {
964                 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
965                         prog, ldap_err2string( rc ), rc );
966                 return( rc );
967         }
968
969         nresponses = nentries = nreferences = nextended = npartial = 0;
970
971         res = NULL;
972
973         while ((rc = ldap_result( ld, LDAP_RES_ANY,
974                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
975                 NULL, &res )) > 0 )
976         {
977                 if( sortattr ) {
978                         (void) ldap_sort_entries( ld, &res,
979                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
980                 }
981
982                 for ( msg = ldap_first_message( ld, res );
983                         msg != NULL;
984                         msg = ldap_next_message( ld, msg ) )
985                 {
986                         if ( nresponses++ ) putchar('\n');
987                         if ( nresponses_psearch >= 0 ) 
988                                 nresponses_psearch++;
989
990                         switch( ldap_msgtype( msg ) ) {
991                         case LDAP_RES_SEARCH_ENTRY:
992                                 nentries++;
993                                 print_entry( ld, msg, attrsonly );
994                                 break;
995
996                         case LDAP_RES_SEARCH_REFERENCE:
997                                 nreferences++;
998                                 print_reference( ld, msg );
999                                 break;
1000
1001                         case LDAP_RES_EXTENDED:
1002                                 nextended++;
1003                                 print_extended( ld, msg );
1004
1005                                 if( ldap_msgid( msg ) == 0 ) {
1006                                         /* unsolicited extended operation */
1007                                         goto done;
1008                                 }
1009
1010                                 if ( cancel_msgid != -1 &&
1011                                                 cancel_msgid == ldap_msgid( msg ) ) {
1012                                         printf(_("Cancelled \n"));
1013                                         printf(_("cancel_msgid = %d\n"), cancel_msgid);
1014                                         goto done;
1015                                 }
1016                                 break;
1017
1018                         case LDAP_RES_SEARCH_RESULT:
1019                                 rc = print_result( ld, msg, 1 );
1020 #ifdef LDAP_CONTROL_PAGEDRESULTS
1021                                 if ( pageSize != 0 ) { 
1022                                         rc = parse_page_control( ld, msg, &cookie );
1023                                 }
1024 #endif
1025
1026                                 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1027                                         break;
1028                                 }
1029
1030                                 goto done;
1031
1032                         case LDAP_RES_INTERMEDIATE:
1033                                 npartial++;
1034                                 ldap_parse_intermediate( ld, msg,
1035                                         &retoid, &retdata, NULL, 0 );
1036
1037                                 nresponses_psearch = 0;
1038
1039                                 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1040                                         printf(_("SyncInfo Received\n"));
1041                                         ldap_memfree( retoid );
1042                                         ber_bvfree( retdata );
1043                                         break;
1044                                 }
1045
1046                                 print_partial( ld, msg );
1047                                 ldap_memfree( retoid );
1048                                 ber_bvfree( retdata );
1049                                 goto done;
1050                         }
1051
1052                         if ( ldapsync && sync_slimit != -1 &&
1053                                         nresponses_psearch >= sync_slimit ) {
1054                                 BerElement *msgidber = NULL;
1055                                 struct berval *msgidvalp = NULL;
1056                                 msgidber = ber_alloc_t(LBER_USE_DER);
1057                                 ber_printf(msgidber, "{i}", msgid);
1058                                 ber_flatten(msgidber, &msgidvalp);
1059                                 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1060                                                 msgidvalp, NULL, NULL, &cancel_msgid);
1061                                 nresponses_psearch = -1;
1062                         }
1063                 }
1064
1065                 ldap_msgfree( res );
1066         }
1067
1068         if ( rc == -1 ) {
1069                 ldap_perror( ld, "ldap_result" );
1070                 return( rc );
1071         }
1072
1073 done:
1074         ldap_msgfree( res );
1075 #ifdef LDAP_CONTROL_PAGEDRESULTS
1076         if ( pageSize != 0 ) { 
1077                 npagedresponses = npagedresponses + nresponses;
1078                 npagedentries = npagedentries + nentries;
1079                 npagedreferences = npagedreferences + nreferences;
1080                 npagedextended = npagedextended + nextended;
1081                 npagedpartial = npagedpartial + npartial;
1082                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1083                         printf( _("\n# numResponses: %d\n"), npagedresponses );
1084                         if( nentries ) printf( _("# numEntries: %d\n"), npagedentries );
1085                         if( nextended ) printf( _("# numExtended: %d\n"), npagedextended );
1086                         if( npartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1087                         if( nreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1088                 }
1089         } else
1090 #endif
1091         if ( ldif < 2 ) {
1092                 printf( _("\n# numResponses: %d\n"), nresponses );
1093                 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1094                 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1095                 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1096                 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1097         }
1098
1099         return( rc );
1100 }
1101
1102 /* This is the proposed new way of doing things.
1103  * It is more efficient, but the API is non-standard.
1104  */
1105 static void
1106 print_entry(
1107         LDAP    *ld,
1108         LDAPMessage     *entry,
1109         int             attrsonly)
1110 {
1111         char            *ufn = NULL;
1112         char    tmpfname[ 256 ];
1113         char    url[ 256 ];
1114         int                     i, rc;
1115         BerElement              *ber = NULL;
1116         struct berval           bv, *bvals, **bvp = &bvals;
1117         LDAPControl **ctrls = NULL;
1118         FILE            *tmpfp;
1119
1120         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1121
1122         if ( ldif < 2 ) {
1123                 ufn = ldap_dn2ufn( bv.bv_val );
1124                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1125         }
1126         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1127
1128         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1129         if( rc != LDAP_SUCCESS ) {
1130                 fprintf(stderr, _("print_entry: %d\n"), rc );
1131                 ldap_perror( ld, "ldap_get_entry_controls" );
1132                 exit( EXIT_FAILURE );
1133         }
1134
1135         if( ctrls ) {
1136                 print_ctrls( ctrls );
1137                 ldap_controls_free( ctrls );
1138         }
1139
1140         if ( includeufn ) {
1141                 if( ufn == NULL ) {
1142                         ufn = ldap_dn2ufn( bv.bv_val );
1143                 }
1144                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1145         }
1146
1147         if( ufn != NULL ) ldap_memfree( ufn );
1148
1149         if ( attrsonly ) bvp = NULL;
1150
1151         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1152                 rc == LDAP_SUCCESS;
1153                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1154         {
1155                 if (bv.bv_val == NULL) break;
1156
1157                 if ( attrsonly ) {
1158                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1159
1160                 } else if ( bvals ) {
1161                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1162                                 if ( vals2tmp > 1 || ( vals2tmp &&
1163                                         ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1164                                 {
1165                                         int tmpfd;
1166                                         /* write value to file */
1167                                         snprintf( tmpfname, sizeof tmpfname,
1168                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1169                                                 tmpdir, bv.bv_val );
1170                                         tmpfp = NULL;
1171
1172                                         tmpfd = mkstemp( tmpfname );
1173
1174                                         if ( tmpfd < 0  ) {
1175                                                 perror( tmpfname );
1176                                                 continue;
1177                                         }
1178
1179                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1180                                                 perror( tmpfname );
1181                                                 continue;
1182                                         }
1183
1184                                         if ( fwrite( bvals[ i ].bv_val,
1185                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1186                                         {
1187                                                 perror( tmpfname );
1188                                                 fclose( tmpfp );
1189                                                 continue;
1190                                         }
1191
1192                                         fclose( tmpfp );
1193
1194                                         snprintf( url, sizeof url, "%s%s", urlpre,
1195                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1196
1197                                         urlize( url );
1198                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1199
1200                                 } else {
1201                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1202                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1203                                 }
1204                         }
1205                         ber_memfree( bvals );
1206                 }
1207         }
1208
1209         if( ber != NULL ) {
1210                 ber_free( ber, 0 );
1211         }
1212 }
1213
1214 static void print_reference(
1215         LDAP *ld,
1216         LDAPMessage *reference )
1217 {
1218         int rc;
1219         char **refs = NULL;
1220         LDAPControl **ctrls;
1221
1222         if( ldif < 2 ) {
1223                 printf(_("# search reference\n"));
1224         }
1225
1226         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1227
1228         if( rc != LDAP_SUCCESS ) {
1229                 ldap_perror(ld, "ldap_parse_reference");
1230                 exit( EXIT_FAILURE );
1231         }
1232
1233         if( refs ) {
1234                 int i;
1235                 for( i=0; refs[i] != NULL; i++ ) {
1236                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1237                                 "ref", refs[i], strlen(refs[i]) );
1238                 }
1239                 ber_memvfree( (void **) refs );
1240         }
1241
1242         if( ctrls ) {
1243                 print_ctrls( ctrls );
1244                 ldap_controls_free( ctrls );
1245         }
1246 }
1247
1248 static void print_extended(
1249         LDAP *ld,
1250         LDAPMessage *extended )
1251 {
1252         int rc;
1253         char *retoid = NULL;
1254         struct berval *retdata = NULL;
1255
1256         if( ldif < 2 ) {
1257                 printf(_("# extended result response\n"));
1258         }
1259
1260         rc = ldap_parse_extended_result( ld, extended,
1261                 &retoid, &retdata, 0 );
1262
1263         if( rc != LDAP_SUCCESS ) {
1264                 ldap_perror(ld, "ldap_parse_extended_result");
1265                 exit( EXIT_FAILURE );
1266         }
1267
1268         if ( ldif < 2 ) {
1269                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1270                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1271         }
1272         ber_memfree( retoid );
1273
1274         if(retdata) {
1275                 if ( ldif < 2 ) {
1276                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1277                                 "data", retdata->bv_val, retdata->bv_len );
1278                 }
1279                 ber_bvfree( retdata );
1280         }
1281
1282         print_result( ld, extended, 0 );
1283 }
1284
1285 static void print_partial(
1286         LDAP *ld,
1287         LDAPMessage *partial )
1288 {
1289         int rc;
1290         char *retoid = NULL;
1291         struct berval *retdata = NULL;
1292         LDAPControl **ctrls = NULL;
1293
1294         if( ldif < 2 ) {
1295                 printf(_("# extended partial response\n"));
1296         }
1297
1298         rc = ldap_parse_intermediate( ld, partial,
1299                 &retoid, &retdata, &ctrls, 0 );
1300
1301         if( rc != LDAP_SUCCESS ) {
1302                 ldap_perror(ld, "ldap_parse_intermediate");
1303                 exit( EXIT_FAILURE );
1304         }
1305
1306         if ( ldif < 2 ) {
1307                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1308                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1309         }
1310
1311         ber_memfree( retoid );
1312
1313         if( retdata ) {
1314                 if ( ldif < 2 ) {
1315                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1316                                 "data", retdata->bv_val, retdata->bv_len );
1317                 }
1318
1319                 ber_bvfree( retdata );
1320         }
1321
1322         if( ctrls ) {
1323                 print_ctrls( ctrls );
1324                 ldap_controls_free( ctrls );
1325         }
1326 }
1327
1328 static int print_result(
1329         LDAP *ld,
1330         LDAPMessage *result, int search )
1331 {
1332         int rc;
1333         int err;
1334         char *matcheddn = NULL;
1335         char *text = NULL;
1336         char **refs = NULL;
1337         LDAPControl **ctrls = NULL;
1338
1339         if( search ) {
1340                 if ( ldif < 2 ) {
1341                         printf(_("# search result\n"));
1342                 }
1343                 if ( ldif < 1 ) {
1344                         printf("%s: %d\n", _("search"), ldap_msgid(result) );
1345                 }
1346         }
1347
1348         rc = ldap_parse_result( ld, result,
1349                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1350
1351         if( rc != LDAP_SUCCESS ) {
1352                 ldap_perror(ld, "ldap_parse_result");
1353                 exit( EXIT_FAILURE );
1354         }
1355
1356
1357         if( !ldif ) {
1358                 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1359
1360         } else if ( err != LDAP_SUCCESS ) {
1361                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1362         }
1363
1364         if( matcheddn ) {
1365                 if( *matcheddn ) {
1366                 if( !ldif ) {
1367                         write_ldif( LDIF_PUT_VALUE,
1368                                 "matchedDN", matcheddn, strlen(matcheddn) );
1369                 } else {
1370                         fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1371                 }
1372                 }
1373
1374                 ber_memfree( matcheddn );
1375         }
1376
1377         if( text ) {
1378                 if( *text ) {
1379                 if( !ldif ) {
1380                         write_ldif( LDIF_PUT_TEXT, "text",
1381                                 text, strlen(text) );
1382                 } else {
1383                         fprintf( stderr, _("Additional information: %s\n"), text );
1384                 }
1385                 }
1386
1387                 ber_memfree( text );
1388         }
1389
1390         if( refs ) {
1391                 int i;
1392                 for( i=0; refs[i] != NULL; i++ ) {
1393                         if( !ldif ) {
1394                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1395                         } else {
1396                                 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1397                         }
1398                 }
1399
1400                 ber_memvfree( (void **) refs );
1401         }
1402
1403         if( ctrls ) {
1404                 print_ctrls( ctrls );
1405                 ldap_controls_free( ctrls );
1406         }
1407
1408         return err;
1409 }
1410
1411 static void print_ctrls(
1412         LDAPControl **ctrls )
1413 {
1414         int i;
1415         for(i=0; ctrls[i] != NULL; i++ ) {
1416                 /* control: OID criticality base64value */
1417                 struct berval *b64 = NULL;
1418                 ber_len_t len;
1419                 char *str;
1420
1421                 len = ldif ? 2 : 0;
1422                 len += strlen( ctrls[i]->ldctl_oid );
1423
1424                 /* add enough for space after OID and the critical value itself */
1425                 len += ctrls[i]->ldctl_iscritical
1426                         ? sizeof("true") : sizeof("false");
1427
1428                 /* convert to base64 */
1429                 if( ctrls[i]->ldctl_value.bv_len ) {
1430                         b64 = ber_memalloc( sizeof(struct berval) );
1431                         
1432                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1433                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1434                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1435
1436                         b64->bv_len = lutil_b64_ntop(
1437                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1438                                 ctrls[i]->ldctl_value.bv_len,
1439                                 b64->bv_val, b64->bv_len );
1440                 }
1441
1442                 if( b64 ) {
1443                         len += 1 + b64->bv_len;
1444                 }
1445
1446                 str = malloc( len + 1 );
1447                 if ( ldif ) {
1448                         strcpy( str, ": " );
1449                 } else {
1450                         str[0] = '\0';
1451                 }
1452                 strcat( str, ctrls[i]->ldctl_oid );
1453                 strcat( str, ctrls[i]->ldctl_iscritical
1454                         ? " true" : " false" );
1455
1456                 if( b64 ) {
1457                         strcat(str, " ");
1458                         strcat(str, b64->bv_val );
1459                 }
1460
1461                 if ( ldif < 2 ) {
1462                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1463                                 "control", str, len );
1464                 }
1465
1466                 free( str );
1467                 ber_bvfree( b64 );
1468         }
1469 }
1470
1471 static int
1472 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1473 {
1474         char    *ldif;
1475
1476         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1477                 return( -1 );
1478         }
1479
1480         fputs( ldif, stdout );
1481         ber_memfree( ldif );
1482
1483         return( 0 );
1484 }
1485
1486
1487 #ifdef LDAP_CONTROL_PAGEDRESULTS
1488 static int 
1489 parse_page_control(
1490         LDAP *ld,
1491         LDAPMessage *result,
1492         struct berval *cookie )
1493 {
1494         int rc;
1495         int err;
1496         LDAPControl **ctrl = NULL;
1497         LDAPControl *ctrlp = NULL;
1498         BerElement *ber;
1499         ber_tag_t tag;
1500         struct berval servercookie = { 0, NULL };
1501
1502         rc = ldap_parse_result( ld, result,
1503                 &err, NULL, NULL, NULL, &ctrl, 0 );
1504
1505         if( rc != LDAP_SUCCESS ) {
1506                 ldap_perror(ld, "ldap_parse_result");
1507                 exit( EXIT_FAILURE );
1508         }
1509
1510         if ( err != LDAP_SUCCESS ) {
1511                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1512         }
1513
1514         if( ctrl ) {
1515                 /* Parse the control value
1516                  * searchResult ::= SEQUENCE {
1517                  *              size    INTEGER (0..maxInt),
1518                  *                              -- result set size estimate from server - unused
1519                  *              cookie  OCTET STRING
1520                  * }
1521                  */
1522                 ctrlp = *ctrl;
1523                 ber = ber_init( &ctrlp->ldctl_value );
1524                 if ( ber == NULL ) {
1525                         fprintf( stderr, _("Internal error.\n") );
1526                         return EXIT_FAILURE;
1527                 }
1528
1529                 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1530                 ber_dupbv( cookie, &servercookie );
1531                 (void) ber_free( ber, 1 );
1532
1533                 if( tag == LBER_ERROR ) {
1534                         fprintf( stderr,
1535                                 _("Paged results response control could not be decoded.\n") );
1536                         return EXIT_FAILURE;
1537                 }
1538
1539                 if( entriesLeft < 0 ) {
1540                         fprintf( stderr,
1541                                 _("Invalid entries estimate in paged results response.\n") );
1542                         return EXIT_FAILURE;
1543                 }
1544
1545                 if ( servercookie.bv_len == 0 ) {
1546                         morePagedResults = 0;
1547                 }
1548
1549                 ldap_controls_free( ctrl );
1550
1551         } else {
1552                 morePagedResults = 0;
1553         }
1554
1555         return err;
1556 }
1557 #endif