]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
ITS#3755 silence strict-aliasing warnings
[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                 int percent = 0;
680         
681                 if ( infile[0] == '-' && infile[1] == '\0' ) {
682                         fp = stdin;
683                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
684                         perror( infile );
685                         return EXIT_FAILURE;
686                 }
687
688                 for( i=0 ; filtpattern[i] ; i++ ) {
689                         if( filtpattern[i] == '%' ) {
690                                 if( percent ) {
691                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
692                                                 filtpattern );
693                                         return EXIT_FAILURE;
694                                 }
695
696                                 percent++;
697
698                                 if( filtpattern[i+1] != 's' ) {
699                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
700                                                 filtpattern );
701                                         return EXIT_FAILURE;
702                                 }
703                         }
704                 }
705         }
706
707         if ( tmpdir == NULL ) {
708                 tmpdir = def_tmpdir;
709
710                 if ( urlpre == NULL )
711                         urlpre = def_urlpre;
712         }
713
714         if( urlpre == NULL ) {
715                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
716
717                 if( urlpre == NULL ) {
718                         perror( "malloc" );
719                         return EXIT_FAILURE;
720                 }
721
722                 sprintf( urlpre, "file:///%s/",
723                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
724
725                 urlize( urlpre );
726         }
727
728         if ( debug )
729                 ldif_debug = debug;
730
731         ld = tool_conn_setup( 0, &private_conn_setup );
732
733         if ( pw_file || want_bindpw ) {
734                 if ( pw_file ) {
735                         rc = lutil_get_filed_password( pw_file, &passwd );
736                         if( rc ) return EXIT_FAILURE;
737                 } else {
738                         passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
739                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
740                 }
741         }
742
743         tool_bind( ld );
744
745 getNextPage:
746         save_nctrls = nctrls;
747         i = nctrls;
748         if ( nctrls > 0
749 #ifdef LDAP_CONTROL_DONTUSECOPY
750                 || dontUseCopy
751 #endif
752                 || domainScope
753                 || pagedResults
754                 || ldapsync
755                 || subentries
756                 || valuesReturnFilter )
757         {
758
759 #ifdef LDAP_CONTROL_DONTUSECOPY
760                 if ( dontUseCopy ) {
761                         if ( ctrl_add() ) {
762                                 return EXIT_FAILURE;
763                         }
764
765                         c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
766                         c[i].ldctl_value.bv_val = NULL;
767                         c[i].ldctl_value.bv_len = 0;
768                         c[i].ldctl_iscritical = dontUseCopy > 1;
769                         i++;
770                 }
771 #endif
772
773                 if ( domainScope ) {
774                         if ( ctrl_add() ) {
775                                 return EXIT_FAILURE;
776                         }
777
778                         c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
779                         c[i].ldctl_value.bv_val = NULL;
780                         c[i].ldctl_value.bv_len = 0;
781                         c[i].ldctl_iscritical = domainScope > 1;
782                         i++;
783                 }
784
785                 if ( subentries ) {
786                         if ( ctrl_add() ) {
787                                 return EXIT_FAILURE;
788                         }
789
790                         if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
791                                 return EXIT_FAILURE;
792                         }
793
794                         err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
795                         if ( err == -1 ) {
796                                 ber_free( seber, 1 );
797                                 fprintf( stderr, _("Subentries control encoding error!\n") );
798                                 return EXIT_FAILURE;
799                         }
800
801                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
802                                 return EXIT_FAILURE;
803                         }
804
805                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
806                         c[i].ldctl_iscritical = subentries < 1;
807                         i++;
808                 }
809
810                 if ( ldapsync ) {
811                         if ( ctrl_add() ) {
812                                 return EXIT_FAILURE;
813                         }
814
815                         if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
816                                 return EXIT_FAILURE;
817                         }
818
819                         if ( sync_cookie.bv_len == 0 ) {
820                                 err = ber_printf( syncber, "{e}", abs(ldapsync) );
821                         } else {
822                                 err = ber_printf( syncber, "{eO}", abs(ldapsync),
823                                                         &sync_cookie );
824                         }
825
826                         if ( err == LBER_ERROR ) {
827                                 ber_free( syncber, 1 );
828                                 fprintf( stderr, _("ldap sync control encoding error!\n") );
829                                 return EXIT_FAILURE;
830                         }
831
832                         if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
833                                 return EXIT_FAILURE;
834                         }
835
836                         c[i].ldctl_oid = LDAP_CONTROL_SYNC;
837                         c[i].ldctl_value = (*syncbvalp);
838                         c[i].ldctl_iscritical = ldapsync < 0;
839                         i++;
840                 }
841
842                 if ( valuesReturnFilter ) {
843                         if ( ctrl_add() ) {
844                                 return EXIT_FAILURE;
845                         }
846
847                         if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
848                                 return EXIT_FAILURE;
849                         }
850
851                         if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
852                                 ber_free( vrber, 1 );
853                                 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
854                                 return EXIT_FAILURE;
855                         }
856
857                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
858                                 return EXIT_FAILURE;
859                         }
860
861                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
862                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
863                         i++;
864                 }
865
866                 if ( pagedResults ) {
867                         if ( ctrl_add() ) {
868                                 return EXIT_FAILURE;
869                         }
870
871                         if ( ldap_create_page_control_value( ld,
872                                 pageSize, &pr_cookie, &c[i].ldctl_value ) )
873                         {
874                                 return EXIT_FAILURE;
875                         }
876
877                         if ( pr_cookie.bv_val != NULL ) {
878                                 ber_memfree( pr_cookie.bv_val );
879                                 pr_cookie.bv_val = NULL;
880                                 pr_cookie.bv_len = 0;
881                         }
882                         
883                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
884                         c[i].ldctl_iscritical = pagedResults > 1;
885                         i++;
886                 }
887         }
888
889         tool_server_controls( ld, c, i );
890
891         ber_free( seber, 1 );
892         ber_free( vrber, 1 );
893
894         /* step back to the original number of controls, so that 
895          * those set while parsing args are preserved */
896         nctrls = save_nctrls;
897
898         if ( verbose ) {
899                 fprintf( stderr, _("filter%s: %s\nrequesting: "),
900                         infile != NULL ? _(" pattern") : "",
901                         filtpattern );
902
903                 if ( attrs == NULL ) {
904                         fprintf( stderr, _("All userApplication attributes") );
905                 } else {
906                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
907                                 fprintf( stderr, "%s ", attrs[ i ] );
908                         }
909                 }
910                 fprintf( stderr, "\n" );
911         }
912
913         if ( ldif == 0 ) {
914                 printf( _("# extended LDIF\n") );
915         } else if ( ldif < 3 ) {
916                 printf( _("version: %d\n\n"), 1 );
917         }
918
919         if (ldif < 2 ) {
920                 char    *realbase = base;
921
922                 if ( realbase == NULL ) {
923                         ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
924                 }
925                 
926                 printf( "#\n" );
927                 printf(_("# LDAPv%d\n"), protocol);
928                 printf(_("# base <%s>%s with scope %s\n"),
929                         realbase ? realbase : "",
930                         ( realbase == NULL || realbase != base ) ? " (default)" : "",
931                         ((scope == LDAP_SCOPE_BASE) ? "baseObject"
932                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
933                                 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
934                                 : "subtree" ))));
935                 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
936                        filtpattern);
937                 printf(_("# requesting: "));
938
939                 if ( attrs == NULL ) {
940                         printf( _("ALL") );
941                 } else {
942                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
943                                 printf( "%s ", attrs[ i ] );
944                         }
945                 }
946
947                 if ( manageDSAit ) {
948                         printf(_("\n# with manageDSAit %scontrol"),
949                                 manageDSAit > 1 ? _("critical ") : "" );
950                 }
951                 if ( noop ) {
952                         printf(_("\n# with noop %scontrol"),
953                                 noop > 1 ? _("critical ") : "" );
954                 }
955                 if ( subentries ) {
956                         printf(_("\n# with subentries %scontrol: %s"),
957                                 subentries < 0 ? _("critical ") : "",
958                                 abs(subentries) == 1 ? "false" : "true" );
959                 }
960                 if ( valuesReturnFilter ) {
961                         printf(_("\n# with valuesReturnFilter %scontrol: %s"),
962                                 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
963                 }
964                 if ( pagedResults ) {
965                         printf(_("\n# with pagedResults %scontrol: size=%d"),
966                                 (pagedResults > 1) ? _("critical ") : "", 
967                                 pageSize );
968                 }
969
970                 printf( _("\n#\n\n") );
971
972                 if ( realbase && realbase != base ) {
973                         ldap_memfree( realbase );
974                 }
975         }
976
977         if ( infile == NULL ) {
978                 rc = dosearch( ld, base, scope, NULL, filtpattern,
979                         attrs, attrsonly, NULL, NULL, NULL, -1 );
980
981         } else {
982                 first = 1;
983                 while ( fgets( line, sizeof( line ), fp ) != NULL ) { 
984                         line[ strlen( line ) - 1 ] = '\0';
985                         if ( !first ) {
986                                 putchar( '\n' );
987                         } else {
988                                 first = 0;
989                         }
990                         rc = dosearch( ld, base, scope, filtpattern, line,
991                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
992
993                         if ( rc != 0 && !contoper ) {
994                                 break;
995                         }
996                 }
997                 if ( fp != stdin ) {
998                         fclose( fp );
999                 }
1000         }
1001
1002         if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1003                 char    buf[6];
1004                 int     i, moreEntries, tmpSize;
1005
1006                 /* Loop to get the next pages when 
1007                  * enter is pressed on the terminal.
1008                  */
1009                 if ( pagePrompt != 0 ) {
1010                         if ( entriesLeft > 0 ) {
1011                                 printf( _("Estimate entries: %d\n"), entriesLeft );
1012                         }
1013                         printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1014                                 (int)pageSize );
1015                         i = 0;
1016                         moreEntries = getchar();
1017                         while ( moreEntries != EOF && moreEntries != '\n' ) { 
1018                                 if ( i < (int)sizeof(buf) - 1 ) {
1019                                         buf[i] = moreEntries;
1020                                         i++;
1021                                 }
1022                                 moreEntries = getchar();
1023                         }
1024                         buf[i] = '\0';
1025
1026                         if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1027                                 int num = sscanf( buf, "%d", &tmpSize );
1028                                 if ( num != 1 ) {
1029                                         fprintf( stderr,
1030                                                 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1031                                         return EXIT_FAILURE;
1032         
1033                                 }
1034                                 pageSize = (ber_int_t)tmpSize;
1035                         }
1036                 }
1037
1038                 goto getNextPage;
1039         }
1040
1041         tool_unbind( ld );
1042         tool_destroy();
1043
1044         if ( c ) {
1045                 for ( ; save_nctrls-- > 0; ) {
1046                         ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1047                 }
1048                 free( c );
1049                 c = NULL;
1050         }
1051
1052         return( rc );
1053 }
1054
1055
1056 static int dosearch(
1057         LDAP    *ld,
1058         char    *base,
1059         int             scope,
1060         char    *filtpatt,
1061         char    *value,
1062         char    **attrs,
1063         int             attrsonly,
1064         LDAPControl **sctrls,
1065         LDAPControl **cctrls,
1066         struct timeval *timeout,
1067         int sizelimit )
1068 {
1069         char                    *filter;
1070         int                     rc;
1071         int                     nresponses;
1072         int                     nentries;
1073         int                     nreferences;
1074         int                     nextended;
1075         int                     npartial;
1076         LDAPMessage             *res, *msg;
1077         ber_int_t               msgid;
1078         char                    *retoid = NULL;
1079         struct berval           *retdata = NULL;
1080         int                     nresponses_psearch = -1;
1081         int                     cancel_msgid = -1;
1082
1083         if( filtpatt != NULL ) {
1084                 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1;
1085                 filter = malloc( max_fsize );
1086                 if( filter == NULL ) {
1087                         perror( "malloc" );
1088                         return EXIT_FAILURE;
1089                 }
1090
1091                 if( snprintf( filter, max_fsize, filtpatt, value ) >= max_fsize ) {
1092                         fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1093                         free( filter );
1094                         return EXIT_FAILURE;
1095                 }
1096
1097                 if ( verbose ) {
1098                         fprintf( stderr, _("filter: %s\n"), filter );
1099                 }
1100
1101                 if( ldif < 2 ) {
1102                         printf( _("#\n# filter: %s\n#\n"), filter );
1103                 }
1104
1105         } else {
1106                 filter = value;
1107         }
1108
1109         if ( dont ) {
1110                 if ( filtpatt != NULL ) {
1111                         free( filter );
1112                 }
1113                 return LDAP_SUCCESS;
1114         }
1115
1116         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1117                 sctrls, cctrls, timeout, sizelimit, &msgid );
1118
1119         if ( filtpatt != NULL ) {
1120                 free( filter );
1121         }
1122
1123         if( rc != LDAP_SUCCESS ) {
1124                 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1125                         prog, ldap_err2string( rc ), rc );
1126                 return( rc );
1127         }
1128
1129         nresponses = nentries = nreferences = nextended = npartial = 0;
1130
1131         res = NULL;
1132
1133         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1134                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1135                 NULL, &res )) > 0 )
1136         {
1137                 rc = tool_check_abandon( ld, msgid );
1138                 if ( rc ) {
1139                         return rc;
1140                 }
1141
1142                 if( sortattr ) {
1143                         (void) ldap_sort_entries( ld, &res,
1144                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1145                 }
1146
1147                 for ( msg = ldap_first_message( ld, res );
1148                         msg != NULL;
1149                         msg = ldap_next_message( ld, msg ) )
1150                 {
1151                         if ( nresponses++ ) putchar('\n');
1152                         if ( nresponses_psearch >= 0 ) 
1153                                 nresponses_psearch++;
1154
1155                         switch( ldap_msgtype( msg ) ) {
1156                         case LDAP_RES_SEARCH_ENTRY:
1157                                 nentries++;
1158                                 print_entry( ld, msg, attrsonly );
1159                                 break;
1160
1161                         case LDAP_RES_SEARCH_REFERENCE:
1162                                 nreferences++;
1163                                 print_reference( ld, msg );
1164                                 break;
1165
1166                         case LDAP_RES_EXTENDED:
1167                                 nextended++;
1168                                 print_extended( ld, msg );
1169
1170                                 if( ldap_msgid( msg ) == 0 ) {
1171                                         /* unsolicited extended operation */
1172                                         goto done;
1173                                 }
1174
1175                                 if ( cancel_msgid != -1 &&
1176                                                 cancel_msgid == ldap_msgid( msg ) ) {
1177                                         printf(_("Cancelled \n"));
1178                                         printf(_("cancel_msgid = %d\n"), cancel_msgid);
1179                                         goto done;
1180                                 }
1181                                 break;
1182
1183                         case LDAP_RES_SEARCH_RESULT:
1184                                 /* pagedResults stuff is dealt with
1185                                  * in tool_print_ctrls(), called by
1186                                  * print_results(). */
1187                                 rc = print_result( ld, msg, 1 );
1188                                 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1189                                         break;
1190                                 }
1191
1192                                 goto done;
1193
1194                         case LDAP_RES_INTERMEDIATE:
1195                                 npartial++;
1196                                 ldap_parse_intermediate( ld, msg,
1197                                         &retoid, &retdata, NULL, 0 );
1198
1199                                 nresponses_psearch = 0;
1200
1201                                 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1202                                         printf(_("SyncInfo Received\n"));
1203                                         ldap_memfree( retoid );
1204                                         ber_bvfree( retdata );
1205                                         break;
1206                                 }
1207
1208                                 print_partial( ld, msg );
1209                                 ldap_memfree( retoid );
1210                                 ber_bvfree( retdata );
1211                                 goto done;
1212                         }
1213
1214                         if ( ldapsync && sync_slimit != -1 &&
1215                                         nresponses_psearch >= sync_slimit ) {
1216                                 BerElement *msgidber = NULL;
1217                                 struct berval *msgidvalp = NULL;
1218                                 msgidber = ber_alloc_t(LBER_USE_DER);
1219                                 ber_printf(msgidber, "{i}", msgid);
1220                                 ber_flatten(msgidber, &msgidvalp);
1221                                 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1222                                         msgidvalp, NULL, NULL, &cancel_msgid);
1223                                 nresponses_psearch = -1;
1224                         }
1225                 }
1226
1227                 ldap_msgfree( res );
1228         }
1229
1230 done:
1231         if ( rc == -1 ) {
1232                 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1233                 return( rc );
1234         }
1235
1236         ldap_msgfree( res );
1237
1238         if ( pagedResults ) { 
1239                 npagedresponses += nresponses;
1240                 npagedentries += nentries;
1241                 npagedextended += nextended;
1242                 npagedpartial += npartial;
1243                 npagedreferences += nreferences;
1244                 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1245                         printf( _("\n# numResponses: %d\n"), npagedresponses );
1246                         if( npagedentries ) {
1247                                 printf( _("# numEntries: %d\n"), npagedentries );
1248                         }
1249                         if( npagedextended ) {
1250                                 printf( _("# numExtended: %d\n"), npagedextended );
1251                         }
1252                         if( npagedpartial ) {
1253                                 printf( _("# numPartial: %d\n"), npagedpartial );
1254                         }
1255                         if( npagedreferences ) {
1256                                 printf( _("# numReferences: %d\n"), npagedreferences );
1257                         }
1258                 }
1259         } else if ( ldif < 2 ) {
1260                 printf( _("\n# numResponses: %d\n"), nresponses );
1261                 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1262                 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1263                 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1264                 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1265         }
1266
1267         return( rc );
1268 }
1269
1270 /* This is the proposed new way of doing things.
1271  * It is more efficient, but the API is non-standard.
1272  */
1273 static void
1274 print_entry(
1275         LDAP    *ld,
1276         LDAPMessage     *entry,
1277         int             attrsonly)
1278 {
1279         char            *ufn = NULL;
1280         char    tmpfname[ 256 ];
1281         char    url[ 256 ];
1282         int                     i, rc;
1283         BerElement              *ber = NULL;
1284         struct berval           bv, *bvals, **bvp = &bvals;
1285         LDAPControl **ctrls = NULL;
1286         FILE            *tmpfp;
1287
1288         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1289
1290         if ( ldif < 2 ) {
1291                 ufn = ldap_dn2ufn( bv.bv_val );
1292                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1293         }
1294         tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1295
1296         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1297         if( rc != LDAP_SUCCESS ) {
1298                 fprintf(stderr, _("print_entry: %d\n"), rc );
1299                 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1300                 exit( EXIT_FAILURE );
1301         }
1302
1303         if( ctrls ) {
1304                 tool_print_ctrls( ld, ctrls );
1305                 ldap_controls_free( ctrls );
1306         }
1307
1308         if ( includeufn ) {
1309                 if( ufn == NULL ) {
1310                         ufn = ldap_dn2ufn( bv.bv_val );
1311                 }
1312                 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1313         }
1314
1315         if( ufn != NULL ) ldap_memfree( ufn );
1316
1317         if ( attrsonly ) bvp = NULL;
1318
1319         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1320                 rc == LDAP_SUCCESS;
1321                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1322         {
1323                 if (bv.bv_val == NULL) break;
1324
1325                 if ( attrsonly ) {
1326                         tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1327
1328                 } else if ( bvals ) {
1329                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1330                                 if ( vals2tmp > 1 || ( vals2tmp &&
1331                                         ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1332                                 {
1333                                         int tmpfd;
1334                                         /* write value to file */
1335                                         snprintf( tmpfname, sizeof tmpfname,
1336                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1337                                                 tmpdir, bv.bv_val );
1338                                         tmpfp = NULL;
1339
1340                                         tmpfd = mkstemp( tmpfname );
1341
1342                                         if ( tmpfd < 0  ) {
1343                                                 perror( tmpfname );
1344                                                 continue;
1345                                         }
1346
1347                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1348                                                 perror( tmpfname );
1349                                                 continue;
1350                                         }
1351
1352                                         if ( fwrite( bvals[ i ].bv_val,
1353                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1354                                         {
1355                                                 perror( tmpfname );
1356                                                 fclose( tmpfp );
1357                                                 continue;
1358                                         }
1359
1360                                         fclose( tmpfp );
1361
1362                                         snprintf( url, sizeof url, "%s%s", urlpre,
1363                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1364
1365                                         urlize( url );
1366                                         tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1367
1368                                 } else {
1369                                         tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1370                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1371                                 }
1372                         }
1373                         ber_memfree( bvals );
1374                 }
1375         }
1376
1377         if( ber != NULL ) {
1378                 ber_free( ber, 0 );
1379         }
1380 }
1381
1382 static void print_reference(
1383         LDAP *ld,
1384         LDAPMessage *reference )
1385 {
1386         int rc;
1387         char **refs = NULL;
1388         LDAPControl **ctrls;
1389
1390         if( ldif < 2 ) {
1391                 printf(_("# search reference\n"));
1392         }
1393
1394         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1395
1396         if( rc != LDAP_SUCCESS ) {
1397                 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1398                 exit( EXIT_FAILURE );
1399         }
1400
1401         if( refs ) {
1402                 int i;
1403                 for( i=0; refs[i] != NULL; i++ ) {
1404                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1405                                 "ref", refs[i], strlen(refs[i]) );
1406                 }
1407                 ber_memvfree( (void **) refs );
1408         }
1409
1410         if( ctrls ) {
1411                 tool_print_ctrls( ld, ctrls );
1412                 ldap_controls_free( ctrls );
1413         }
1414 }
1415
1416 static void print_extended(
1417         LDAP *ld,
1418         LDAPMessage *extended )
1419 {
1420         int rc;
1421         char *retoid = NULL;
1422         struct berval *retdata = NULL;
1423
1424         if( ldif < 2 ) {
1425                 printf(_("# extended result response\n"));
1426         }
1427
1428         rc = ldap_parse_extended_result( ld, extended,
1429                 &retoid, &retdata, 0 );
1430
1431         if( rc != LDAP_SUCCESS ) {
1432                 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1433                 exit( EXIT_FAILURE );
1434         }
1435
1436         if ( ldif < 2 ) {
1437                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1438                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1439         }
1440         ber_memfree( retoid );
1441
1442         if(retdata) {
1443                 if ( ldif < 2 ) {
1444                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1445                                 "data", retdata->bv_val, retdata->bv_len );
1446                 }
1447                 ber_bvfree( retdata );
1448         }
1449
1450         print_result( ld, extended, 0 );
1451 }
1452
1453 static void print_partial(
1454         LDAP *ld,
1455         LDAPMessage *partial )
1456 {
1457         int rc;
1458         char *retoid = NULL;
1459         struct berval *retdata = NULL;
1460         LDAPControl **ctrls = NULL;
1461
1462         if( ldif < 2 ) {
1463                 printf(_("# extended partial response\n"));
1464         }
1465
1466         rc = ldap_parse_intermediate( ld, partial,
1467                 &retoid, &retdata, &ctrls, 0 );
1468
1469         if( rc != LDAP_SUCCESS ) {
1470                 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1471                 exit( EXIT_FAILURE );
1472         }
1473
1474         if ( ldif < 2 ) {
1475                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1476                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1477         }
1478
1479         ber_memfree( retoid );
1480
1481         if( retdata ) {
1482                 if ( ldif < 2 ) {
1483                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1484                                 "data", retdata->bv_val, retdata->bv_len );
1485                 }
1486
1487                 ber_bvfree( retdata );
1488         }
1489
1490         if( ctrls ) {
1491                 tool_print_ctrls( ld, ctrls );
1492                 ldap_controls_free( ctrls );
1493         }
1494 }
1495
1496 static int print_result(
1497         LDAP *ld,
1498         LDAPMessage *result, int search )
1499 {
1500         int rc;
1501         int err;
1502         char *matcheddn = NULL;
1503         char *text = NULL;
1504         char **refs = NULL;
1505         LDAPControl **ctrls = NULL;
1506
1507         if( search ) {
1508                 if ( ldif < 2 ) {
1509                         printf(_("# search result\n"));
1510                 }
1511                 if ( ldif < 1 ) {
1512                         printf("%s: %d\n", _("search"), ldap_msgid(result) );
1513                 }
1514         }
1515
1516         rc = ldap_parse_result( ld, result,
1517                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1518
1519         if( rc != LDAP_SUCCESS ) {
1520                 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1521                 exit( EXIT_FAILURE );
1522         }
1523
1524
1525         if( !ldif ) {
1526                 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1527
1528         } else if ( err != LDAP_SUCCESS ) {
1529                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1530         }
1531
1532         if( matcheddn ) {
1533                 if( *matcheddn ) {
1534                 if( !ldif ) {
1535                         tool_write_ldif( LDIF_PUT_VALUE,
1536                                 "matchedDN", matcheddn, strlen(matcheddn) );
1537                 } else {
1538                         fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1539                 }
1540                 }
1541
1542                 ber_memfree( matcheddn );
1543         }
1544
1545         if( text ) {
1546                 if( *text ) {
1547                         if( !ldif ) {
1548                                 if ( err == LDAP_PARTIAL_RESULTS ) {
1549                                         char    *line;
1550
1551                                         for ( line = text; line != NULL; ) {
1552                                                 char    *next = strchr( line, '\n' );
1553
1554                                                 tool_write_ldif( LDIF_PUT_TEXT,
1555                                                         "text", line,
1556                                                         next ? next - line : strlen( line ) );
1557
1558                                                 line = next ? next + 1 : NULL;
1559                                         }
1560
1561                                 } else {
1562                                         tool_write_ldif( LDIF_PUT_TEXT, "text",
1563                                                 text, strlen(text) );
1564                                 }
1565                         } else {
1566                                 fprintf( stderr, _("Additional information: %s\n"), text );
1567                         }
1568                 }
1569
1570                 ber_memfree( text );
1571         }
1572
1573         if( refs ) {
1574                 int i;
1575                 for( i=0; refs[i] != NULL; i++ ) {
1576                         if( !ldif ) {
1577                                 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1578                         } else {
1579                                 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1580                         }
1581                 }
1582
1583                 ber_memvfree( (void **) refs );
1584         }
1585
1586         pr_morePagedResults = 0;
1587
1588         if( ctrls ) {
1589                 tool_print_ctrls( ld, ctrls );
1590                 ldap_controls_free( ctrls );
1591         }
1592
1593         return err;
1594 }
1595