]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
c65ddafc93860d7accf9059c4f8c87f029c9dad9
[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-2006 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_DONTUSECOPY
126         fprintf( stderr, _("             !dontUseCopy                (Don't Use Copy)\n"));
127 #endif
128         fprintf( stderr, _("             [!]domainScope              (domain scope)\n"));
129         fprintf( stderr, _("             [!]mv=<filter>              (matched values filter)\n"));
130         fprintf( stderr, _("             [!]pr=<size>[/prompt|noprompt]   (paged results/prompt)\n"));
131         fprintf( stderr, _("             [!]subentries[=true|false]  (subentries)\n"));
132         fprintf( stderr, _("             [!]sync=ro[/<cookie>]            (LDAP Sync refreshOnly)\n"));
133         fprintf( stderr, _("                     rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
134         fprintf( stderr, _("             [!]<oid>=:<value>           (generic control; no response handling)\n"));
135         fprintf( stderr, _("  -F prefix  URL prefix for files (default: %s)\n"), def_urlpre);
136         fprintf( stderr, _("  -l limit   time limit (in seconds, or \"none\" or \"max\") for search\n"));
137         fprintf( stderr, _("  -L         print responses in LDIFv1 format\n"));
138         fprintf( stderr, _("  -LL        print responses in LDIF format without comments\n"));
139         fprintf( stderr, _("  -LLL       print responses in LDIF format without comments\n"));
140         fprintf( stderr, _("             and version\n"));
141         fprintf( stderr, _("  -s scope   one of base, one, sub or children (search scope)\n"));
142         fprintf( stderr, _("  -S attr    sort the results by attribute `attr'\n"));
143         fprintf( stderr, _("  -t         write binary values to files in temporary directory\n"));
144         fprintf( stderr, _("  -tt        write all values to files in temporary directory\n"));
145         fprintf( stderr, _("  -T path    write files to directory specified by path (default: %s)\n"), def_tmpdir);
146         fprintf( stderr, _("  -u         include User Friendly entry names in the output\n"));
147         fprintf( stderr, _("  -z limit   size limit (in entries, or \"none\" or \"max\") for search\n"));
148         tool_common_usage();
149         exit( EXIT_FAILURE );
150 }
151
152 static void print_entry LDAP_P((
153         LDAP    *ld,
154         LDAPMessage     *entry,
155         int             attrsonly));
156
157 static void print_reference(
158         LDAP *ld,
159         LDAPMessage *reference );
160
161 static void print_extended(
162         LDAP *ld,
163         LDAPMessage *extended );
164
165 static void print_partial(
166         LDAP *ld,
167         LDAPMessage *partial );
168
169 static int print_result(
170         LDAP *ld,
171         LDAPMessage *result,
172         int search );
173
174 static int dosearch LDAP_P((
175         LDAP    *ld,
176         char    *base,
177         int             scope,
178         char    *filtpatt,
179         char    *value,
180         char    **attrs,
181         int             attrsonly,
182         LDAPControl **sctrls,
183         LDAPControl **cctrls,
184         struct timeval *timeout,
185         int     sizelimit ));
186
187 static char *tmpdir = NULL;
188 static char *urlpre = NULL;
189 static char     *base = NULL;
190 static char     *sortattr = NULL;
191 static int  includeufn, vals2tmp = 0;
192
193 static int subentries = 0, valuesReturnFilter = 0;
194 static char     *vrFilter = NULL;
195
196 #ifdef LDAP_CONTROL_DONTUSECOPY
197 static int dontUseCopy = 0;
198 #endif
199
200 static int domainScope = 0;
201
202 static int ldapsync = 0;
203 static struct berval sync_cookie = { 0, NULL };
204 static int sync_slimit = -1;
205
206 static int pagedResults = 0;
207 static int pagePrompt = 1;
208 static ber_int_t pageSize = 0;
209 static ber_int_t entriesLeft = 0;
210 static ber_int_t morePagedResults = 1;
211 static struct berval page_cookie = { 0, NULL };
212 static int npagedresponses;
213 static int npagedentries;
214 static int npagedreferences;
215 static int npagedextended;
216 static int npagedpartial;
217
218 static LDAPControl *c = NULL;
219 static int nctrls = 0;
220 static int save_nctrls = 0;
221
222 static int
223 ctrl_add( void )
224 {
225         LDAPControl     *tmpc;
226
227         nctrls++;
228         tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
229         if ( tmpc == NULL ) {
230                 nctrls--;
231                 fprintf( stderr,
232                         _("unable to make room for control; out of memory?\n"));
233                 return -1;
234         }
235         c = tmpc;
236
237         return 0;
238 }
239
240 static int
241 is_oid( const char *s )
242 {
243         int             first = 1;
244
245         if ( !isdigit( s[ 0 ] ) ) {
246                 return 0;
247         }
248
249         for ( ; s[ 0 ]; s++ ) {
250                 if ( s[ 0 ] == '.' ) {
251                         if ( s[ 1 ] == '\0' ) {
252                                 return 0;
253                         }
254                         first = 1;
255                         continue;
256                 }
257
258                 if ( !isdigit( s[ 0 ] ) ) {
259                         return 0;
260                 }
261
262                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
263                         return 0;
264                 }
265                 first = 0;
266         }
267
268         return 1;
269 }
270
271 static int parse_page_control(
272         LDAP *ld,
273         LDAPMessage *result,
274         struct berval *cookie );
275
276 static void
277 urlize(char *url)
278 {
279         char *p;
280
281         if (*LDAP_DIRSEP != '/') {
282                 for (p = url; *p; p++) {
283                         if (*p == *LDAP_DIRSEP)
284                                 *p = '/';
285                 }
286         }
287 }
288
289
290 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
291         "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
292
293 int
294 handle_private_option( int i )
295 {
296         int crit, ival;
297         char *control, *cvalue, *next;
298         switch ( i ) {
299         case 'a':       /* set alias deref option */
300                 if ( strcasecmp( optarg, "never" ) == 0 ) {
301                         deref = LDAP_DEREF_NEVER;
302                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
303                         deref = LDAP_DEREF_SEARCHING;
304                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
305                         deref = LDAP_DEREF_FINDING;
306                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
307                         deref = LDAP_DEREF_ALWAYS;
308                 } else {
309                         fprintf( stderr,
310                                 _("alias deref should be never, search, find, or always\n") );
311                         usage();
312                 }
313                 break;
314         case 'A':       /* retrieve attribute names only -- no values */
315                 ++attrsonly;
316                 break;
317         case 'b': /* search base */
318                 base = ber_strdup( optarg );
319                 break;
320         case 'E': /* search extensions */
321                 if( protocol == LDAP_VERSION2 ) {
322                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
323                                 prog, protocol );
324                         exit( EXIT_FAILURE );
325                 }
326
327                 /* should be extended to support comma separated list of
328                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
329                  */
330
331                 crit = 0;
332                 cvalue = NULL;
333                 if( optarg[0] == '!' ) {
334                         crit = 1;
335                         optarg++;
336                 }
337
338                 control = ber_strdup( optarg );
339                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
340                         *cvalue++ = '\0';
341                 }
342
343                 if ( strcasecmp( control, "mv" ) == 0 ) {
344                         /* ValuesReturnFilter control */
345                         if( valuesReturnFilter ) {
346                                 fprintf( stderr,
347                                         _("ValuesReturnFilter previously specified\n"));
348                                 exit( EXIT_FAILURE );
349                         }
350                         valuesReturnFilter= 1 + crit;
351
352                         if ( cvalue == NULL ) {
353                                 fprintf( stderr,
354                                         _("missing filter in ValuesReturnFilter control\n"));
355                                 exit( EXIT_FAILURE );
356                         }
357
358                         vrFilter = cvalue;
359                         protocol = LDAP_VERSION3;
360
361                 } else if ( strcasecmp( control, "pr" ) == 0 ) {
362                         int num, tmp;
363                         /* PagedResults control */
364                         if ( pagedResults != 0 ) {
365                                 fprintf( stderr,
366                                         _("PagedResultsControl previously specified\n") );
367                                 exit( EXIT_FAILURE );
368                         }
369
370                         if( cvalue != NULL ) {
371                                 char *promptp;
372
373                                 promptp = strchr( cvalue, '/' );
374                                 if ( promptp != NULL ) {
375                                         *promptp++ = '\0';
376                                         if ( strcasecmp( promptp, "prompt" ) == 0 ) {
377                                                 pagePrompt = 1;
378                                         } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
379                                                 pagePrompt = 0;
380                                         } else {
381                                                 fprintf( stderr,
382                                                         _("Invalid value for PagedResultsControl,"
383                                                         " %s/%s.\n"), cvalue, promptp );
384                                                 exit( EXIT_FAILURE );
385                                         }
386                                 }
387                                 num = sscanf( cvalue, "%d", &tmp );
388                                 if ( num != 1 ) {
389                                         fprintf( stderr,
390                                                 _("Invalid value for PagedResultsControl, %s.\n"),
391                                                 cvalue );
392                                         exit( EXIT_FAILURE );
393                                 }
394                         } else {
395                                 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
396                                 exit( EXIT_FAILURE );
397                         }
398                         pageSize = (ber_int_t) tmp;
399                         pagedResults = 1 + crit;
400
401 #ifdef LDAP_CONTROL_DONTUSECOPY
402                 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
403                         if( dontUseCopy ) {
404                                 fprintf( stderr,
405                                         _("dontUseCopy control previously specified\n"));
406                                 exit( EXIT_FAILURE );
407                         }
408                         if( cvalue != NULL ) {
409                                 fprintf( stderr,
410                                  _("dontUseCopy: no control value expected\n") );
411                                 usage();
412                         }
413                         if( !crit ) {
414                                 fprintf( stderr,
415                                  _("dontUseCopy: critical flag required\n") );
416                                 usage();
417                         }
418
419                         dontUseCopy = 1 + crit;
420 #endif
421                 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
422                         if( domainScope ) {
423                                 fprintf( stderr,
424                                         _("domainScope control previously specified\n"));
425                                 exit( EXIT_FAILURE );
426                         }
427                         if( cvalue != NULL ) {
428                                 fprintf( stderr,
429                                  _("domainScope: no control value expected\n") );
430                                 usage();
431                         }
432
433                         domainScope = 1 + crit;
434
435                 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
436                         if( subentries ) {
437                                 fprintf( stderr,
438                                         _("subentries control previously specified\n"));
439                                 exit( EXIT_FAILURE );
440                         }
441                         if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
442                                 subentries = 2;
443                         } else if ( strcasecmp( cvalue, "false") == 0 ) {
444                                 subentries = 1;
445                         } else {
446                                 fprintf( stderr,
447                                         _("subentries control value \"%s\" invalid\n"),
448                                         cvalue );
449                                 exit( EXIT_FAILURE );
450                         }
451                         if( crit ) subentries *= -1;
452
453                 } else if ( strcasecmp( control, "sync" ) == 0 ) {
454                         char *cookiep;
455                         char *slimitp;
456                         if ( ldapsync ) {
457                                 fprintf( stderr, _("sync control previously specified\n") );
458                                 exit( EXIT_FAILURE );
459                         }
460                         if ( cvalue == NULL ) {
461                                 fprintf( stderr, _("missing specification of sync control\n"));
462                                 exit( EXIT_FAILURE );
463                         }
464                         if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
465                                 ldapsync = LDAP_SYNC_REFRESH_ONLY;
466                                 cookiep = strchr( cvalue, '/' );
467                                 if ( cookiep != NULL ) {
468                                         cookiep++;
469                                         if ( *cookiep != '\0' ) {
470                                                 ber_str2bv( cookiep, 0, 0, &sync_cookie );
471                                         }
472                                 }
473                         } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
474                                 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
475                                 cookiep = strchr( cvalue, '/' );
476                                 if ( cookiep != NULL ) {
477                                         *cookiep++ = '\0';      
478                                         cvalue = cookiep;
479                                 }
480                                 slimitp = strchr( cvalue, '/' );
481                                 if ( slimitp != NULL ) {
482                                         *slimitp++ = '\0';
483                                 }
484                                 if ( cookiep != NULL && *cookiep != '\0' )
485                                         ber_str2bv( cookiep, 0, 0, &sync_cookie );
486                                 if ( slimitp != NULL && *slimitp != '\0' ) {
487                                         ival = strtol( slimitp, &next, 10 );
488                                         if ( next == NULL || next[0] != '\0' ) {
489                                                 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
490                                                 exit( EXIT_FAILURE );
491                                         }
492                                         sync_slimit = ival;
493                                 }
494                         } else {
495                                 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
496                                         cvalue );
497                                 exit( EXIT_FAILURE );
498                         }
499                         if ( crit ) ldapsync *= -1;
500
501                 } else if ( is_oid( control ) ) {
502                         if ( ctrl_add() ) {
503                                 exit( EXIT_FAILURE );
504                         }
505
506                         /* OID */
507                         c[ nctrls - 1 ].ldctl_oid = control;
508
509                         /* value */
510                         if ( cvalue == NULL ) {
511                                 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
512                                 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
513
514                         } else if ( cvalue[ 0 ] == ':' ) {
515                                 struct berval   type;
516                                 struct berval   value;
517                                 int             freeval;
518
519                                 cvalue++;
520
521                                 /* dummy type "x"
522                                  * to use ldif_parse_line2() */
523                                 cvalue[ -2 ] = 'x';
524                                 ldif_parse_line2( &cvalue[ -2 ], &type,
525                                         &value, &freeval );
526                                 cvalue[ -2 ] = '\0';
527
528                                 if ( freeval ) {
529                                         c[ nctrls - 1 ].ldctl_value = value;
530
531                                 } else {
532                                         ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
533                                 }
534                         }
535
536                         /* criticality */
537                         c[ nctrls - 1 ].ldctl_iscritical = crit;
538
539                 } else {
540                         fprintf( stderr, _("Invalid search extension name: %s\n"),
541                                 control );
542                         usage();
543                 }
544                 break;
545         case 'F':       /* uri prefix */
546                 if( urlpre ) free( urlpre );
547                 urlpre = strdup( optarg );
548                 break;
549         case 'l':       /* time limit */
550                 if ( strcasecmp( optarg, "none" ) == 0 ) {
551                         timelimit = 0;
552
553                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
554                         timelimit = LDAP_MAXINT;
555
556                 } else {
557                         ival = strtol( optarg, &next, 10 );
558                         if ( next == NULL || next[0] != '\0' ) {
559                                 fprintf( stderr,
560                                         _("Unable to parse time limit \"%s\"\n"), optarg );
561                                 exit( EXIT_FAILURE );
562                         }
563                         timelimit = ival;
564                 }
565                 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
566                         fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
567                                 prog, timelimit );
568                         exit( EXIT_FAILURE );
569                 }
570                 break;
571         case 'L':       /* print entries in LDIF format */
572                 ++ldif;
573                 break;
574         case 's':       /* search scope */
575                 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
576                         scope = LDAP_SCOPE_BASE;
577                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
578                         scope = LDAP_SCOPE_ONELEVEL;
579                 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
580                         || ( strcasecmp( optarg, "children" ) == 0 ))
581                 {
582                         scope = LDAP_SCOPE_SUBORDINATE;
583                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
584                         scope = LDAP_SCOPE_SUBTREE;
585                 } else {
586                         fprintf( stderr, _("scope should be base, one, or sub\n") );
587                         usage();
588                 }
589                 break;
590         case 'S':       /* sort attribute */
591                 sortattr = strdup( optarg );
592                 break;
593         case 't':       /* write attribute values to TMPDIR files */
594                 ++vals2tmp;
595                 break;
596         case 'T':       /* tmpdir */
597                 if( tmpdir ) free( tmpdir );
598                 tmpdir = strdup( optarg );
599                 break;
600         case 'u':       /* include UFN */
601                 ++includeufn;
602                 break;
603         case 'z':       /* size limit */
604                 if ( strcasecmp( optarg, "none" ) == 0 ) {
605                         sizelimit = 0;
606
607                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
608                         sizelimit = LDAP_MAXINT;
609
610                 } else {
611                         ival = strtol( optarg, &next, 10 );
612                         if ( next == NULL || next[0] != '\0' ) {
613                                 fprintf( stderr,
614                                         _("Unable to parse size limit \"%s\"\n"), optarg );
615                                 exit( EXIT_FAILURE );
616                         }
617                         sizelimit = ival;
618                 }
619                 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
620                         fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
621                                 prog, sizelimit );
622                         exit( EXIT_FAILURE );
623                 }
624                 break;
625         default:
626                 return 0;
627         }
628         return 1;
629 }
630
631
632 static void
633 private_conn_setup( LDAP *ld )
634 {
635         if (deref != -1 &&
636                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
637                         != LDAP_OPT_SUCCESS )
638         {
639                 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
640                 exit( EXIT_FAILURE );
641         }
642         if (timelimit > 0 &&
643                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
644                         != LDAP_OPT_SUCCESS )
645         {
646                 fprintf( stderr,
647                         _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
648                 exit( EXIT_FAILURE );
649         }
650         if (sizelimit > 0 &&
651                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
652                         != LDAP_OPT_SUCCESS )
653         {
654                 fprintf( stderr,
655                         _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
656                 exit( EXIT_FAILURE );
657         }
658 }
659
660 int
661 main( int argc, char **argv )
662 {
663         char            *filtpattern, **attrs = NULL, line[BUFSIZ];
664         FILE            *fp = NULL;
665         int                     rc, i, first;
666         LDAP            *ld = NULL;
667         BerElement      *seber = NULL, *vrber = NULL, *prber = NULL;
668
669         BerElement      *syncber = NULL;
670         struct berval   *syncbvalp = NULL;
671
672         tool_init();
673
674         npagedresponses = npagedentries = npagedreferences =
675                 npagedextended = npagedpartial = 0;
676
677         prog = lutil_progname( "ldapsearch", argc, argv );
678
679         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
680            (def_tmpdir = getenv("TMP")) == NULL &&
681            (def_tmpdir = getenv("TEMP")) == NULL )
682         {
683                 def_tmpdir = LDAP_TMPDIR;
684         }
685
686         if ( !*def_tmpdir )
687                 def_tmpdir = LDAP_TMPDIR;
688
689         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
690
691         if( def_urlpre == NULL ) {
692                 perror( "malloc" );
693                 return EXIT_FAILURE;
694         }
695
696         sprintf( def_urlpre, "file:///%s/",
697                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
698
699         urlize( def_urlpre );
700
701         tool_args( argc, argv );
702
703         if (( argc - optind < 1 ) ||
704                 ( *argv[optind] != '(' /*')'*/ &&
705                 ( strchr( argv[optind], '=' ) == NULL ) ) )
706         {
707                 filtpattern = "(objectclass=*)";
708         } else {
709                 filtpattern = argv[optind++];
710         }
711
712         if ( argv[optind] != NULL ) {
713                 attrs = &argv[optind];
714         }
715
716         if ( infile != NULL ) {
717                 if ( infile[0] == '-' && infile[1] == '\0' ) {
718                         fp = stdin;
719                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
720                         perror( infile );
721                         return EXIT_FAILURE;
722                 }
723         }
724
725         if ( tmpdir == NULL ) {
726                 tmpdir = def_tmpdir;
727
728                 if ( urlpre == NULL )
729                         urlpre = def_urlpre;
730         }
731
732         if( urlpre == NULL ) {
733                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
734
735                 if( urlpre == NULL ) {
736                         perror( "malloc" );
737                         return EXIT_FAILURE;
738                 }
739
740                 sprintf( urlpre, "file:///%s/",
741                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
742
743                 urlize( urlpre );
744         }
745
746         if ( debug )
747                 ldif_debug = debug;
748
749         ld = tool_conn_setup( 0, &private_conn_setup );
750
751         if ( pw_file || want_bindpw ) {
752                 if ( pw_file ) {
753                         rc = lutil_get_filed_password( pw_file, &passwd );
754                         if( rc ) return EXIT_FAILURE;
755                 } else {
756                         passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
757                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
758                 }
759         }
760
761         tool_bind( ld );
762
763 getNextPage:
764         if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
765 #ifdef LDAP_CONTROL_DONTUSECOPY
766                 || dontUseCopy
767 #endif
768                 || domainScope || pagedResults
769 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
770                 || chaining
771 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
772                 || ldapsync
773                 || subentries || valuesReturnFilter )
774         {
775                 int err;
776                 int i = nctrls;
777                 save_nctrls = nctrls;
778
779 #ifdef LDAP_CONTROL_DONTUSECOPY
780                 if ( dontUseCopy ) {
781                         if ( ctrl_add() ) {
782                                 return EXIT_FAILURE;
783                         }
784
785                         c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
786                         c[i].ldctl_value.bv_val = NULL;
787                         c[i].ldctl_value.bv_len = 0;
788                         c[i].ldctl_iscritical = dontUseCopy > 1;
789                         i++;
790                 }
791 #endif
792
793                 if ( domainScope ) {
794                         if ( ctrl_add() ) {
795                                 return EXIT_FAILURE;
796                         }
797
798                         c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
799                         c[i].ldctl_value.bv_val = NULL;
800                         c[i].ldctl_value.bv_len = 0;
801                         c[i].ldctl_iscritical = domainScope > 1;
802                         i++;
803                 }
804
805                 if ( subentries ) {
806                         if ( ctrl_add() ) {
807                                 return EXIT_FAILURE;
808                         }
809
810                         if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
811                                 return EXIT_FAILURE;
812                         }
813
814                         err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
815                         if ( err == -1 ) {
816                                 ber_free( seber, 1 );
817                                 fprintf( stderr, _("Subentries control encoding error!\n") );
818                                 return EXIT_FAILURE;
819                         }
820
821                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
822                                 return EXIT_FAILURE;
823                         }
824
825                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
826                         c[i].ldctl_iscritical = subentries < 1;
827                         i++;
828                 }
829
830                 if ( ldapsync ) {
831                         if ( ctrl_add() ) {
832                                 return EXIT_FAILURE;
833                         }
834
835                         if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
836                                 return EXIT_FAILURE;
837                         }
838
839                         if ( sync_cookie.bv_len == 0 ) {
840                                 err = ber_printf( syncber, "{e}", abs(ldapsync) );
841                         } else {
842                                 err = ber_printf( syncber, "{eO}", abs(ldapsync),
843                                                         &sync_cookie );
844                         }
845
846                         if ( err == LBER_ERROR ) {
847                                 ber_free( syncber, 1 );
848                                 fprintf( stderr, _("ldap sync control encoding error!\n") );
849                                 return EXIT_FAILURE;
850                         }
851
852                         if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
853                                 return EXIT_FAILURE;
854                         }
855
856                         c[i].ldctl_oid = LDAP_CONTROL_SYNC;
857                         c[i].ldctl_value = (*syncbvalp);
858                         c[i].ldctl_iscritical = ldapsync < 0;
859                         i++;
860                 }
861
862                 if ( valuesReturnFilter ) {
863                         if ( ctrl_add() ) {
864                                 return EXIT_FAILURE;
865                         }
866
867                         if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
868                                 return EXIT_FAILURE;
869                         }
870
871                         if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
872                                 ber_free( vrber, 1 );
873                                 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
874                                 return EXIT_FAILURE;
875                         }
876
877                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
878                                 return EXIT_FAILURE;
879                         }
880
881                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
882                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
883                         i++;
884                 }
885
886                 if ( pagedResults ) {
887                         if ( ctrl_add() ) {
888                                 return EXIT_FAILURE;
889                         }
890
891                         if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
892                                 return EXIT_FAILURE;
893                         }
894
895                         ber_printf( prber, "{iO}", pageSize, &page_cookie );
896                         if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
897                                 return EXIT_FAILURE;
898                         }
899                         if ( page_cookie.bv_val != NULL ) {
900                                 ber_memfree( page_cookie.bv_val );
901                                 page_cookie.bv_val = NULL;
902                         }
903                         
904                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
905                         c[i].ldctl_iscritical = pagedResults > 1;
906                         i++;
907                 }
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                 ber_free( seber, 1 );
916                 ber_free( vrber, 1 );
917                 ber_free( prber, 1 );
918         }
919         
920         if ( verbose ) {
921                 fprintf( stderr, _("filter%s: %s\nrequesting: "),
922                         infile != NULL ? _(" pattern") : "",
923                         filtpattern );
924
925                 if ( attrs == NULL ) {
926                         fprintf( stderr, _("All userApplication attributes") );
927                 } else {
928                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
929                                 fprintf( stderr, "%s ", attrs[ i ] );
930                         }
931                 }
932                 fprintf( stderr, "\n" );
933         }
934
935         if ( ldif == 0 ) {
936                 printf( _("# extended LDIF\n") );
937         } else if ( ldif < 3 ) {
938                 printf( _("version: %d\n\n"), 1 );
939         }
940
941         if (ldif < 2 ) {
942                 printf( "#\n" );
943                 printf(_("# LDAPv%d\n"), protocol);
944                 printf(_("# base <%s> with scope %s\n"),
945                         base ? base : "",
946                         ((scope == LDAP_SCOPE_BASE) ? "baseObject"
947                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
948                                 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
949                                 : "subtree" ))));
950                 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
951                        filtpattern);
952                 printf(_("# requesting: "));
953
954                 if ( attrs == NULL ) {
955                         printf( _("ALL") );
956                 } else {
957                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
958                                 printf( "%s ", attrs[ i ] );
959                         }
960                 }
961
962                 if ( manageDSAit ) {
963                         printf(_("\n# with manageDSAit %scontrol"),
964                                 manageDSAit > 1 ? _("critical ") : "" );
965                 }
966                 if ( noop ) {
967                         printf(_("\n# with noop %scontrol"),
968                                 noop > 1 ? _("critical ") : "" );
969                 }
970                 if ( subentries ) {
971                         printf(_("\n# with subentries %scontrol: %s"),
972                                 subentries < 0 ? _("critical ") : "",
973                                 abs(subentries) == 1 ? "false" : "true" );
974                 }
975                 if ( valuesReturnFilter ) {
976                         printf(_("\n# with valuesReturnFilter %scontrol: %s"),
977                                 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
978                 }
979                 if ( pagedResults ) {
980                         printf(_("\n# with pagedResults %scontrol: size=%d"),
981                                 (pagedResults > 1) ? _("critical ") : "", 
982                                 pageSize );
983                 }
984
985                 printf( _("\n#\n\n") );
986         }
987
988         if ( infile == NULL ) {
989                 rc = dosearch( ld, base, scope, NULL, filtpattern,
990                         attrs, attrsonly, NULL, NULL, NULL, -1 );
991
992         } else {
993                 rc = 0;
994                 first = 1;
995                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
996                         line[ strlen( line ) - 1 ] = '\0';
997                         if ( !first ) {
998                                 putchar( '\n' );
999                         } else {
1000                                 first = 0;
1001                         }
1002                         rc = dosearch( ld, base, scope, filtpattern, line,
1003                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1004                 }
1005                 if ( fp != stdin ) {
1006                         fclose( fp );
1007                 }
1008         }
1009
1010         if (( rc == LDAP_SUCCESS ) && pageSize && morePagedResults ) {
1011                 char    buf[6];
1012                 int     i, moreEntries, tmpSize;
1013
1014                 /* Loop to get the next pages when 
1015                  * enter is pressed on the terminal.
1016                  */
1017                 if ( pagePrompt != 0 ) {
1018                         if ( entriesLeft > 0 ) {
1019                                 printf( _("Estimate entries: %d\n"), entriesLeft );
1020                         }
1021                         printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1022                                 (int)pageSize );
1023                         i = 0;
1024                         moreEntries = getchar();
1025                         while ( moreEntries != EOF && moreEntries != '\n' ) { 
1026                                 if ( i < (int)sizeof(buf) - 1 ) {
1027                                         buf[i] = moreEntries;
1028                                         i++;
1029                                 }
1030                                 moreEntries = getchar();
1031                         }
1032                         buf[i] = '\0';
1033
1034                         if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1035                                 int num = sscanf( buf, "%d", &tmpSize );
1036                                 if ( num != 1 ) {
1037                                         fprintf( stderr,
1038                                                 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1039                                         return EXIT_FAILURE;
1040         
1041                                 }
1042                                 pageSize = (ber_int_t)tmpSize;
1043                         }
1044                 }
1045
1046                 goto getNextPage;
1047         }
1048
1049         tool_unbind( ld );
1050         tool_destroy();
1051
1052         if ( c ) {
1053                 for ( ; save_nctrls-- > 0; ) {
1054                         ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1055                 }
1056                 free( c );
1057                 c = NULL;
1058         }
1059
1060         return( rc );
1061 }
1062
1063
1064 static int dosearch(
1065         LDAP    *ld,
1066         char    *base,
1067         int             scope,
1068         char    *filtpatt,
1069         char    *value,
1070         char    **attrs,
1071         int             attrsonly,
1072         LDAPControl **sctrls,
1073         LDAPControl **cctrls,
1074         struct timeval *timeout,
1075         int sizelimit )
1076 {
1077         char                    *filter;
1078         int                     rc;
1079         int                     nresponses;
1080         int                     nentries;
1081         int                     nreferences;
1082         int                     nextended;
1083         int                     npartial;
1084         LDAPMessage             *res, *msg;
1085         ber_int_t               msgid;
1086         char                    *retoid = NULL;
1087         struct berval           *retdata = NULL;
1088         int                     nresponses_psearch = -1;
1089         int                     cancel_msgid = -1;
1090
1091         if( filtpatt != NULL ) {
1092                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1093                 if( filter == NULL ) {
1094                         perror( "malloc" );
1095                         return EXIT_FAILURE;
1096                 }
1097
1098                 sprintf( filter, filtpatt, value );
1099
1100                 if ( verbose ) {
1101                         fprintf( stderr, _("filter: %s\n"), filter );
1102                 }
1103
1104                 if( ldif < 2 ) {
1105                         printf( _("#\n# filter: %s\n#\n"), filter );
1106                 }
1107
1108         } else {
1109                 filter = value;
1110         }
1111
1112         if ( not ) {
1113                 return LDAP_SUCCESS;
1114         }
1115
1116         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1117                 sctrls, cctrls, timeout, sizelimit, &msgid );
1118
1119         if ( filtpatt != NULL ) {
1120                 free( filter );
1121         }
1122
1123         if( rc != LDAP_SUCCESS ) {
1124                 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1125                         prog, ldap_err2string( rc ), rc );
1126                 return( rc );
1127         }
1128
1129         nresponses = nentries = nreferences = nextended = npartial = 0;
1130
1131         res = NULL;
1132
1133         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1134                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1135                 NULL, &res )) > 0 )
1136         {
1137                 rc = tool_check_abandon( ld, msgid );
1138                 if ( rc ) {
1139                         return rc;
1140                 }
1141
1142                 if( sortattr ) {
1143                         (void) ldap_sort_entries( ld, &res,
1144                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1145                 }
1146
1147                 for ( msg = ldap_first_message( ld, res );
1148                         msg != NULL;
1149                         msg = ldap_next_message( ld, msg ) )
1150                 {
1151                         if ( nresponses++ ) putchar('\n');
1152                         if ( nresponses_psearch >= 0 ) 
1153                                 nresponses_psearch++;
1154
1155                         switch( ldap_msgtype( msg ) ) {
1156                         case LDAP_RES_SEARCH_ENTRY:
1157                                 nentries++;
1158                                 print_entry( ld, msg, attrsonly );
1159                                 break;
1160
1161                         case LDAP_RES_SEARCH_REFERENCE:
1162                                 nreferences++;
1163                                 print_reference( ld, msg );
1164                                 break;
1165
1166                         case LDAP_RES_EXTENDED:
1167                                 nextended++;
1168                                 print_extended( ld, msg );
1169
1170                                 if( ldap_msgid( msg ) == 0 ) {
1171                                         /* unsolicited extended operation */
1172                                         goto done;
1173                                 }
1174
1175                                 if ( cancel_msgid != -1 &&
1176                                                 cancel_msgid == ldap_msgid( msg ) ) {
1177                                         printf(_("Cancelled \n"));
1178                                         printf(_("cancel_msgid = %d\n"), cancel_msgid);
1179                                         goto done;
1180                                 }
1181                                 break;
1182
1183                         case LDAP_RES_SEARCH_RESULT:
1184                                 rc = print_result( ld, msg, 1 );
1185                                 if ( pageSize != 0 ) {
1186                                         if ( rc == LDAP_SUCCESS ) {
1187                                                 rc = parse_page_control( ld, msg, &page_cookie );
1188                                         } else {
1189                                                 morePagedResults = 0;
1190                                         }
1191                                 } else {
1192                                         morePagedResults = 0;
1193                                 }
1194
1195                                 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1196                                         break;
1197                                 }
1198
1199                                 goto done;
1200
1201                         case LDAP_RES_INTERMEDIATE:
1202                                 npartial++;
1203                                 ldap_parse_intermediate( ld, msg,
1204                                         &retoid, &retdata, NULL, 0 );
1205
1206                                 nresponses_psearch = 0;
1207
1208                                 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1209                                         printf(_("SyncInfo Received\n"));
1210                                         ldap_memfree( retoid );
1211                                         ber_bvfree( retdata );
1212                                         break;
1213                                 }
1214
1215                                 print_partial( ld, msg );
1216                                 ldap_memfree( retoid );
1217                                 ber_bvfree( retdata );
1218                                 goto done;
1219                         }
1220
1221                         if ( ldapsync && sync_slimit != -1 &&
1222                                         nresponses_psearch >= sync_slimit ) {
1223                                 BerElement *msgidber = NULL;
1224                                 struct berval *msgidvalp = NULL;
1225                                 msgidber = ber_alloc_t(LBER_USE_DER);
1226                                 ber_printf(msgidber, "{i}", msgid);
1227                                 ber_flatten(msgidber, &msgidvalp);
1228                                 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1229                                                 msgidvalp, NULL, NULL, &cancel_msgid);
1230                                 nresponses_psearch = -1;
1231                         }
1232                 }
1233
1234                 ldap_msgfree( res );
1235         }
1236
1237 done:
1238         if ( rc == -1 ) {
1239                 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1240                 return( rc );
1241         }
1242
1243         ldap_msgfree( res );
1244
1245         if ( pagedResults ) { 
1246                 npagedresponses += nresponses;
1247                 npagedentries += nentries;
1248                 npagedextended += nextended;
1249                 npagedpartial += npartial;
1250                 npagedreferences += nreferences;
1251                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1252                         printf( _("\n# numResponses: %d\n"), npagedresponses );
1253                         if( npagedentries ) {
1254                                 printf( _("# numEntries: %d\n"), npagedentries );
1255                         }
1256                         if( npagedextended ) {
1257                                 printf( _("# numExtended: %d\n"), npagedextended );
1258                         }
1259                         if( npagedpartial ) {
1260                                 printf( _("# numPartial: %d\n"), npagedpartial );
1261                         }
1262                         if( npagedreferences ) {
1263                                 printf( _("# numReferences: %d\n"), npagedreferences );
1264                         }
1265                 }
1266         } else 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 static int 
1587 parse_page_control(
1588         LDAP *ld,
1589         LDAPMessage *result,
1590         struct berval *cookie )
1591 {
1592         int rc;
1593         int err;
1594         LDAPControl **ctrl = NULL;
1595         LDAPControl *ctrlp = NULL;
1596         BerElement *ber;
1597         ber_tag_t tag;
1598
1599         rc = ldap_parse_result( ld, result,
1600                 &err, NULL, NULL, NULL, &ctrl, 0 );
1601
1602         if( rc != LDAP_SUCCESS ) {
1603                 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1604                 exit( EXIT_FAILURE );
1605         }
1606
1607         if ( err != LDAP_SUCCESS ) {
1608                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1609         }
1610
1611         if( ctrl ) {
1612                 /* Parse the control value
1613                  * searchResult ::= SEQUENCE {
1614                  *              size    INTEGER (0..maxInt),
1615                  *                              -- result set size estimate from server - unused
1616                  *              cookie  OCTET STRING
1617                  * }
1618                  */
1619                 ctrlp = *ctrl;
1620                 ber = ber_init( &ctrlp->ldctl_value );
1621                 if ( ber == NULL ) {
1622                         fprintf( stderr, _("Internal error.\n") );
1623                         return EXIT_FAILURE;
1624                 }
1625
1626                 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1627                 (void) ber_free( ber, 1 );
1628
1629                 if( tag == LBER_ERROR ) {
1630                         fprintf( stderr,
1631                                 _("Paged results response control could not be decoded.\n") );
1632                         return EXIT_FAILURE;
1633                 }
1634
1635                 if( entriesLeft < 0 ) {
1636                         fprintf( stderr,
1637                                 _("Invalid entries estimate in paged results response.\n") );
1638                         return EXIT_FAILURE;
1639                 }
1640
1641                 if ( cookie->bv_len == 0 ) {
1642                         morePagedResults = 0;
1643                 }
1644
1645                 ldap_controls_free( ctrl );
1646
1647         } else {
1648                 morePagedResults = 0;
1649         }
1650
1651         return err;
1652 }