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