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