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