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