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