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