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