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