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