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