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