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