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