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