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