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