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