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