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