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