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