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