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