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