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