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