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