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