]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Fix typo in derefcrit control
[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-2009 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                         if ( specs == NULL ) {
515                                 fprintf( stderr, _("deref specs \"%s\" invalid\n"),
516                                         cvalue );
517                                 exit( EXIT_FAILURE );
518                         }
519                         for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ )
520                                 /* count'em */
521
522                         ds = ldap_memcalloc( ispecs + 1, sizeof( LDAPDerefSpec ) );
523                         if ( ds == NULL ) {
524                                 perror( "malloc" );
525                                 exit( EXIT_FAILURE );
526                         }
527
528                         for ( ispecs = 0; specs[ ispecs ] != NULL; ispecs++ ) {
529                                 char *ptr;
530
531                                 ptr = strchr( specs[ ispecs ], ':' );
532                                 if ( ptr == NULL ) {
533                                         fprintf( stderr, _("deref specs \"%s\" invalid\n"),
534                                                 cvalue );
535                                         exit( EXIT_FAILURE );
536                                 }
537
538                                 ds[ ispecs ].derefAttr = specs[ ispecs ];
539                                 *ptr++ = '\0';
540                                 ds[ ispecs ].attributes = ldap_str2charray( ptr, "," );
541                         }
542
543                         derefcrit = 1 + crit;
544
545                         ldap_memfree( specs );
546 #endif /* LDAP_CONTROL_X_DEREF */
547
548                 } else if ( tool_is_oid( control ) ) {
549                         if ( c != NULL ) {
550                                 int i;
551                                 for ( i = 0; c[ i ].ldctl_oid != NULL; i++ ) {
552                                         if ( strcmp( control, c[ i ].ldctl_oid ) == 0 ) {
553                                                 fprintf( stderr, "%s control previously specified\n", control );
554                                                 exit( EXIT_FAILURE );
555                                         }
556                                 }
557                         }
558
559                         if ( ctrl_add() ) {
560                                 exit( EXIT_FAILURE );
561                         }
562
563                         /* OID */
564                         c[ nctrls - 1 ].ldctl_oid = control;
565
566                         /* value */
567                         if ( cvalue == NULL ) {
568                                 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
569                                 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
570
571                         } else if ( cvalue[ 0 ] == ':' ) {
572                                 struct berval   type;
573                                 struct berval   value;
574                                 int             freeval;
575
576                                 cvalue++;
577
578                                 /* dummy type "x"
579                                  * to use ldif_parse_line2() */
580                                 cvalue[ -2 ] = 'x';
581                                 ldif_parse_line2( &cvalue[ -2 ], &type,
582                                         &value, &freeval );
583                                 cvalue[ -2 ] = '\0';
584
585                                 if ( freeval ) {
586                                         c[ nctrls - 1 ].ldctl_value = value;
587
588                                 } else {
589                                         ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
590                                 }
591                         }
592
593                         /* criticality */
594                         c[ nctrls - 1 ].ldctl_iscritical = crit;
595
596                 } else {
597                         fprintf( stderr, _("Invalid search extension name: %s\n"),
598                                 control );
599                         usage();
600                 }
601                 break;
602         case 'F':       /* uri prefix */
603                 if( urlpre ) free( urlpre );
604                 urlpre = strdup( optarg );
605                 break;
606         case 'l':       /* time limit */
607                 if ( strcasecmp( optarg, "none" ) == 0 ) {
608                         timelimit = 0;
609
610                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
611                         timelimit = LDAP_MAXINT;
612
613                 } else {
614                         ival = strtol( optarg, &next, 10 );
615                         if ( next == NULL || next[0] != '\0' ) {
616                                 fprintf( stderr,
617                                         _("Unable to parse time limit \"%s\"\n"), optarg );
618                                 exit( EXIT_FAILURE );
619                         }
620                         timelimit = ival;
621                 }
622                 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
623                         fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
624                                 prog, timelimit );
625                         exit( EXIT_FAILURE );
626                 }
627                 break;
628         case 'L':       /* print entries in LDIF format */
629                 ++ldif;
630                 break;
631         case 's':       /* search scope */
632                 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
633                         scope = LDAP_SCOPE_BASE;
634                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
635                         scope = LDAP_SCOPE_ONELEVEL;
636                 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
637                         || ( strcasecmp( optarg, "children" ) == 0 ))
638                 {
639                         scope = LDAP_SCOPE_SUBORDINATE;
640                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
641                         scope = LDAP_SCOPE_SUBTREE;
642                 } else {
643                         fprintf( stderr, _("scope should be base, one, or sub\n") );
644                         usage();
645                 }
646                 break;
647         case 'S':       /* sort attribute */
648                 sortattr = strdup( optarg );
649                 break;
650         case 't':       /* write attribute values to TMPDIR files */
651                 ++vals2tmp;
652                 break;
653         case 'T':       /* tmpdir */
654                 if( tmpdir ) free( tmpdir );
655                 tmpdir = strdup( optarg );
656                 break;
657         case 'u':       /* include UFN */
658                 ++includeufn;
659                 break;
660         case 'z':       /* size limit */
661                 if ( strcasecmp( optarg, "none" ) == 0 ) {
662                         sizelimit = 0;
663
664                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
665                         sizelimit = LDAP_MAXINT;
666
667                 } else {
668                         ival = strtol( optarg, &next, 10 );
669                         if ( next == NULL || next[0] != '\0' ) {
670                                 fprintf( stderr,
671                                         _("Unable to parse size limit \"%s\"\n"), optarg );
672                                 exit( EXIT_FAILURE );
673                         }
674                         sizelimit = ival;
675                 }
676                 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
677                         fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
678                                 prog, sizelimit );
679                         exit( EXIT_FAILURE );
680                 }
681                 break;
682         default:
683                 return 0;
684         }
685         return 1;
686 }
687
688
689 static void
690 private_conn_setup( LDAP *ld )
691 {
692         if (deref != -1 &&
693                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
694                         != LDAP_OPT_SUCCESS )
695         {
696                 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
697                 exit( EXIT_FAILURE );
698         }
699         if (timelimit > 0 &&
700                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
701                         != LDAP_OPT_SUCCESS )
702         {
703                 fprintf( stderr,
704                         _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
705                 exit( EXIT_FAILURE );
706         }
707         if (sizelimit > 0 &&
708                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
709                         != LDAP_OPT_SUCCESS )
710         {
711                 fprintf( stderr,
712                         _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
713                 exit( EXIT_FAILURE );
714         }
715 }
716
717 int
718 main( int argc, char **argv )
719 {
720         char            *filtpattern, **attrs = NULL, line[BUFSIZ];
721         FILE            *fp = NULL;
722         int                     rc, rc1, i, first;
723         LDAP            *ld = NULL;
724         BerElement      *seber = NULL, *vrber = NULL;
725
726         BerElement      *syncber = NULL;
727         struct berval   *syncbvalp = NULL;
728         int             err;
729
730         tool_init( TOOL_SEARCH );
731
732         npagedresponses = npagedentries = npagedreferences =
733                 npagedextended = npagedpartial = 0;
734
735         prog = lutil_progname( "ldapsearch", argc, argv );
736
737         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
738            (def_tmpdir = getenv("TMP")) == NULL &&
739            (def_tmpdir = getenv("TEMP")) == NULL )
740         {
741                 def_tmpdir = LDAP_TMPDIR;
742         }
743
744         if ( !*def_tmpdir )
745                 def_tmpdir = LDAP_TMPDIR;
746
747         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
748
749         if( def_urlpre == NULL ) {
750                 perror( "malloc" );
751                 return EXIT_FAILURE;
752         }
753
754         sprintf( def_urlpre, "file:///%s/",
755                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
756
757         urlize( def_urlpre );
758
759         tool_args( argc, argv );
760
761         if (( argc - optind < 1 ) ||
762                 ( *argv[optind] != '(' /*')'*/ &&
763                 ( strchr( argv[optind], '=' ) == NULL ) ) )
764         {
765                 filtpattern = "(objectclass=*)";
766         } else {
767                 filtpattern = argv[optind++];
768         }
769
770         if ( argv[optind] != NULL ) {
771                 attrs = &argv[optind];
772         }
773
774         if ( infile != NULL ) {
775                 int percent = 0;
776         
777                 if ( infile[0] == '-' && infile[1] == '\0' ) {
778                         fp = stdin;
779                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
780                         perror( infile );
781                         return EXIT_FAILURE;
782                 }
783
784                 for( i=0 ; filtpattern[i] ; i++ ) {
785                         if( filtpattern[i] == '%' ) {
786                                 if( percent ) {
787                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
788                                                 filtpattern );
789                                         return EXIT_FAILURE;
790                                 }
791
792                                 percent++;
793
794                                 if( filtpattern[i+1] != 's' ) {
795                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
796                                                 filtpattern );
797                                         return EXIT_FAILURE;
798                                 }
799                         }
800                 }
801         }
802
803         if ( tmpdir == NULL ) {
804                 tmpdir = def_tmpdir;
805
806                 if ( urlpre == NULL )
807                         urlpre = def_urlpre;
808         }
809
810         if( urlpre == NULL ) {
811                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
812
813                 if( urlpre == NULL ) {
814                         perror( "malloc" );
815                         return EXIT_FAILURE;
816                 }
817
818                 sprintf( urlpre, "file:///%s/",
819                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
820
821                 urlize( urlpre );
822         }
823
824         if ( debug )
825                 ldif_debug = debug;
826
827         ld = tool_conn_setup( 0, &private_conn_setup );
828
829         if ( pw_file || want_bindpw ) {
830                 if ( pw_file ) {
831                         rc = lutil_get_filed_password( pw_file, &passwd );
832                         if( rc ) return EXIT_FAILURE;
833                 } else {
834                         passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
835                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
836                 }
837         }
838
839         tool_bind( ld );
840
841 getNextPage:
842         save_nctrls = nctrls;
843         i = nctrls;
844         if ( nctrls > 0
845 #ifdef LDAP_CONTROL_DONTUSECOPY
846                 || dontUseCopy
847 #endif
848 #ifdef LDAP_CONTROL_X_DEREF
849                 || derefcrit
850 #endif
851                 || domainScope
852                 || pagedResults
853                 || ldapsync
854                 || sss
855                 || subentries
856                 || valuesReturnFilter )
857         {
858
859 #ifdef LDAP_CONTROL_DONTUSECOPY
860                 if ( dontUseCopy ) {
861                         if ( ctrl_add() ) {
862                                 return EXIT_FAILURE;
863                         }
864
865                         c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
866                         c[i].ldctl_value.bv_val = NULL;
867                         c[i].ldctl_value.bv_len = 0;
868                         c[i].ldctl_iscritical = dontUseCopy == 2;
869                         i++;
870                 }
871 #endif
872
873                 if ( domainScope ) {
874                         if ( ctrl_add() ) {
875                                 return EXIT_FAILURE;
876                         }
877
878                         c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
879                         c[i].ldctl_value.bv_val = NULL;
880                         c[i].ldctl_value.bv_len = 0;
881                         c[i].ldctl_iscritical = domainScope > 1;
882                         i++;
883                 }
884
885                 if ( subentries ) {
886                         if ( ctrl_add() ) {
887                                 return EXIT_FAILURE;
888                         }
889
890                         if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
891                                 return EXIT_FAILURE;
892                         }
893
894                         err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
895                         if ( err == -1 ) {
896                                 ber_free( seber, 1 );
897                                 fprintf( stderr, _("Subentries control encoding error!\n") );
898                                 return EXIT_FAILURE;
899                         }
900
901                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
902                                 return EXIT_FAILURE;
903                         }
904
905                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
906                         c[i].ldctl_iscritical = subentries < 1;
907                         i++;
908                 }
909
910                 if ( ldapsync ) {
911                         if ( ctrl_add() ) {
912                                 return EXIT_FAILURE;
913                         }
914
915                         if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
916                                 return EXIT_FAILURE;
917                         }
918
919                         if ( sync_cookie.bv_len == 0 ) {
920                                 err = ber_printf( syncber, "{e}", abs(ldapsync) );
921                         } else {
922                                 err = ber_printf( syncber, "{eO}", abs(ldapsync),
923                                                         &sync_cookie );
924                         }
925
926                         if ( err == -1 ) {
927                                 ber_free( syncber, 1 );
928                                 fprintf( stderr, _("ldap sync control encoding error!\n") );
929                                 return EXIT_FAILURE;
930                         }
931
932                         if ( ber_flatten( syncber, &syncbvalp ) == -1 ) {
933                                 return EXIT_FAILURE;
934                         }
935
936                         c[i].ldctl_oid = LDAP_CONTROL_SYNC;
937                         c[i].ldctl_value = (*syncbvalp);
938                         c[i].ldctl_iscritical = ldapsync < 0;
939                         i++;
940                 }
941
942                 if ( valuesReturnFilter ) {
943                         if ( ctrl_add() ) {
944                                 return EXIT_FAILURE;
945                         }
946
947                         if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
948                                 return EXIT_FAILURE;
949                         }
950
951                         if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
952                                 ber_free( vrber, 1 );
953                                 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
954                                 return EXIT_FAILURE;
955                         }
956
957                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
958                                 return EXIT_FAILURE;
959                         }
960
961                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
962                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
963                         i++;
964                 }
965
966                 if ( pagedResults ) {
967                         if ( ctrl_add() ) {
968                                 return EXIT_FAILURE;
969                         }
970
971                         if ( ldap_create_page_control_value( ld,
972                                 pageSize, &pr_cookie, &c[i].ldctl_value ) )
973                         {
974                                 return EXIT_FAILURE;
975                         }
976
977                         if ( pr_cookie.bv_val != NULL ) {
978                                 ber_memfree( pr_cookie.bv_val );
979                                 pr_cookie.bv_val = NULL;
980                                 pr_cookie.bv_len = 0;
981                         }
982                         
983                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
984                         c[i].ldctl_iscritical = pagedResults > 1;
985                         i++;
986                 }
987
988                 if ( sss ) {
989                         if ( ctrl_add() ) {
990                                 return EXIT_FAILURE;
991                         }
992
993                         if ( ldap_create_sort_control_value( ld,
994                                 sss_keys, &c[i].ldctl_value ) )
995                         {
996                                 return EXIT_FAILURE;
997                         }
998
999                         c[i].ldctl_oid = LDAP_CONTROL_SORTREQUEST;
1000                         c[i].ldctl_iscritical = sss > 1;
1001                         i++;
1002                 }
1003
1004 #ifdef LDAP_CONTROL_X_DEREF
1005                 if ( derefcrit ) {
1006                         if ( derefval.bv_val == NULL ) {
1007                                 int i;
1008
1009                                 assert( ds != NULL );
1010
1011                                 if ( ldap_create_deref_control_value( ld, ds, &derefval ) != LDAP_SUCCESS ) {
1012                                         return EXIT_FAILURE;
1013                                 }
1014
1015                                 for ( i = 0; ds[ i ].derefAttr != NULL; i++ ) {
1016                                         ldap_memfree( ds[ i ].derefAttr );
1017                                         ldap_charray_free( ds[ i ].attributes );
1018                                 }
1019                                 ldap_memfree( ds );
1020                                 ds = NULL;
1021                         }
1022
1023                         if ( ctrl_add() ) {
1024                                 exit( EXIT_FAILURE );
1025                         }
1026
1027                         c[ i ].ldctl_iscritical = derefcrit > 1;
1028                         c[ i ].ldctl_oid = LDAP_CONTROL_X_DEREF;
1029                         c[ i ].ldctl_value = derefval;
1030                         i++;
1031                 }
1032 #endif /* LDAP_CONTROL_X_DEREF */
1033         }
1034
1035         tool_server_controls( ld, c, i );
1036
1037         if ( seber ) ber_free( seber, 1 );
1038         if ( vrber ) ber_free( vrber, 1 );
1039
1040         /* step back to the original number of controls, so that 
1041          * those set while parsing args are preserved */
1042         nctrls = save_nctrls;
1043
1044         if ( verbose ) {
1045                 fprintf( stderr, _("filter%s: %s\nrequesting: "),
1046                         infile != NULL ? _(" pattern") : "",
1047                         filtpattern );
1048
1049                 if ( attrs == NULL ) {
1050                         fprintf( stderr, _("All userApplication attributes") );
1051                 } else {
1052                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1053                                 fprintf( stderr, "%s ", attrs[ i ] );
1054                         }
1055                 }
1056                 fprintf( stderr, "\n" );
1057         }
1058
1059         if ( ldif == 0 ) {
1060                 printf( _("# extended LDIF\n") );
1061         } else if ( ldif < 3 ) {
1062                 printf( _("version: %d\n\n"), 1 );
1063         }
1064
1065         if (ldif < 2 ) {
1066                 char    *realbase = base;
1067
1068                 if ( realbase == NULL ) {
1069                         ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)(char *)&realbase );
1070                 }
1071                 
1072                 printf( "#\n" );
1073                 printf(_("# LDAPv%d\n"), protocol);
1074                 printf(_("# base <%s>%s with scope %s\n"),
1075                         realbase ? realbase : "",
1076                         ( realbase == NULL || realbase != base ) ? " (default)" : "",
1077                         ((scope == LDAP_SCOPE_BASE) ? "baseObject"
1078                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
1079                                 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
1080                                 : "subtree" ))));
1081                 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
1082                        filtpattern);
1083                 printf(_("# requesting: "));
1084
1085                 if ( attrs == NULL ) {
1086                         printf( _("ALL") );
1087                 } else {
1088                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1089                                 printf( "%s ", attrs[ i ] );
1090                         }
1091                 }
1092
1093                 if ( manageDSAit ) {
1094                         printf(_("\n# with manageDSAit %scontrol"),
1095                                 manageDSAit > 1 ? _("critical ") : "" );
1096                 }
1097                 if ( noop ) {
1098                         printf(_("\n# with noop %scontrol"),
1099                                 noop > 1 ? _("critical ") : "" );
1100                 }
1101                 if ( subentries ) {
1102                         printf(_("\n# with subentries %scontrol: %s"),
1103                                 subentries < 0 ? _("critical ") : "",
1104                                 abs(subentries) == 1 ? "false" : "true" );
1105                 }
1106                 if ( valuesReturnFilter ) {
1107                         printf(_("\n# with valuesReturnFilter %scontrol: %s"),
1108                                 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
1109                 }
1110                 if ( pagedResults ) {
1111                         printf(_("\n# with pagedResults %scontrol: size=%d"),
1112                                 (pagedResults > 1) ? _("critical ") : "", 
1113                                 pageSize );
1114                 }
1115                 if ( sss ) {
1116                         printf(_("\n# with server side sorting %scontrol"),
1117                                 sss > 1 ? _("critical ") : "" );
1118                 }
1119 #ifdef LDAP_CONTROL_X_DEREF
1120                 if ( derefcrit ) {
1121                         printf(_("\n# with dereference %scontrol"),
1122                                 derefcrit > 1 ? _("critical ") : "" );
1123                 }
1124 #endif
1125
1126                 printf( _("\n#\n\n") );
1127
1128                 if ( realbase && realbase != base ) {
1129                         ldap_memfree( realbase );
1130                 }
1131         }
1132
1133         if ( infile == NULL ) {
1134                 rc = dosearch( ld, base, scope, NULL, filtpattern,
1135                         attrs, attrsonly, NULL, NULL, NULL, -1 );
1136
1137         } else {
1138                 rc = 0;
1139                 first = 1;
1140                 while ( fgets( line, sizeof( line ), fp ) != NULL ) { 
1141                         line[ strlen( line ) - 1 ] = '\0';
1142                         if ( !first ) {
1143                                 putchar( '\n' );
1144                         } else {
1145                                 first = 0;
1146                         }
1147                         rc1 = dosearch( ld, base, scope, filtpattern, line,
1148                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1149
1150                         if ( rc1 != 0 ) {
1151                                 rc = rc1;
1152                                 if ( !contoper )
1153                                         break;
1154                         }
1155                 }
1156                 if ( fp != stdin ) {
1157                         fclose( fp );
1158                 }
1159         }
1160
1161         if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1162                 char    buf[6];
1163                 int     i, moreEntries, tmpSize;
1164
1165                 /* Loop to get the next pages when 
1166                  * enter is pressed on the terminal.
1167                  */
1168                 if ( pagePrompt != 0 ) {
1169                         if ( entriesLeft > 0 ) {
1170                                 printf( _("Estimate entries: %d\n"), entriesLeft );
1171                         }
1172                         printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1173                                 (int)pageSize );
1174                         i = 0;
1175                         moreEntries = getchar();
1176                         while ( moreEntries != EOF && moreEntries != '\n' ) { 
1177                                 if ( i < (int)sizeof(buf) - 1 ) {
1178                                         buf[i] = moreEntries;
1179                                         i++;
1180                                 }
1181                                 moreEntries = getchar();
1182                         }
1183                         buf[i] = '\0';
1184
1185                         if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1186                                 int num = sscanf( buf, "%d", &tmpSize );
1187                                 if ( num != 1 ) {
1188                                         fprintf( stderr,
1189                                                 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1190                                         return EXIT_FAILURE;
1191         
1192                                 }
1193                                 pageSize = (ber_int_t)tmpSize;
1194                         }
1195                 }
1196
1197                 goto getNextPage;
1198         }
1199
1200         tool_unbind( ld );
1201         tool_destroy();
1202         if ( base != NULL ) {
1203                 ber_memfree( base );
1204         }
1205         if ( control != NULL ) {
1206                 ber_memfree( control );
1207         }
1208         if ( sss_keys != NULL ) {
1209                 ldap_free_sort_keylist( sss_keys );
1210         }
1211         if ( derefval.bv_val != NULL ) {
1212                 ldap_memfree( derefval.bv_val );
1213         }
1214
1215         if ( c ) {
1216                 for ( ; save_nctrls-- > 0; ) {
1217                         ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1218                 }
1219                 free( c );
1220                 c = NULL;
1221         }
1222
1223         return( rc );
1224 }
1225
1226
1227 static int dosearch(
1228         LDAP    *ld,
1229         char    *base,
1230         int             scope,
1231         char    *filtpatt,
1232         char    *value,
1233         char    **attrs,
1234         int             attrsonly,
1235         LDAPControl **sctrls,
1236         LDAPControl **cctrls,
1237         struct timeval *timeout,
1238         int sizelimit )
1239 {
1240         char                    *filter;
1241         int                     rc;
1242         int                     nresponses;
1243         int                     nentries;
1244         int                     nreferences;
1245         int                     nextended;
1246         int                     npartial;
1247         LDAPMessage             *res, *msg;
1248         ber_int_t               msgid;
1249         char                    *retoid = NULL;
1250         struct berval           *retdata = NULL;
1251         int                     nresponses_psearch = -1;
1252         int                     cancel_msgid = -1;
1253
1254         if( filtpatt != NULL ) {
1255                 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1, outlen;
1256                 filter = malloc( max_fsize );
1257                 if( filter == NULL ) {
1258                         perror( "malloc" );
1259                         return EXIT_FAILURE;
1260                 }
1261
1262                 outlen = snprintf( filter, max_fsize, filtpatt, value );
1263                 if( outlen >= max_fsize ) {
1264                         fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1265                         free( filter );
1266                         return EXIT_FAILURE;
1267                 }
1268
1269                 if ( verbose ) {
1270                         fprintf( stderr, _("filter: %s\n"), filter );
1271                 }
1272
1273                 if( ldif < 2 ) {
1274                         printf( _("#\n# filter: %s\n#\n"), filter );
1275                 }
1276
1277         } else {
1278                 filter = value;
1279         }
1280
1281         if ( dont ) {
1282                 if ( filtpatt != NULL ) {
1283                         free( filter );
1284                 }
1285                 return LDAP_SUCCESS;
1286         }
1287
1288         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1289                 sctrls, cctrls, timeout, sizelimit, &msgid );
1290
1291         if ( filtpatt != NULL ) {
1292                 free( filter );
1293         }
1294
1295         if( rc != LDAP_SUCCESS ) {
1296                 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1297                         prog, ldap_err2string( rc ), rc );
1298                 return( rc );
1299         }
1300
1301         nresponses = nentries = nreferences = nextended = npartial = 0;
1302
1303         res = NULL;
1304
1305         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1306                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1307                 NULL, &res )) > 0 )
1308         {
1309                 rc = tool_check_abandon( ld, msgid );
1310                 if ( rc ) {
1311                         return rc;
1312                 }
1313
1314                 if( sortattr ) {
1315                         (void) ldap_sort_entries( ld, &res,
1316                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1317                 }
1318
1319                 for ( msg = ldap_first_message( ld, res );
1320                         msg != NULL;
1321                         msg = ldap_next_message( ld, msg ) )
1322                 {
1323                         if ( nresponses++ ) putchar('\n');
1324                         if ( nresponses_psearch >= 0 ) 
1325                                 nresponses_psearch++;
1326
1327                         switch( ldap_msgtype( msg ) ) {
1328                         case LDAP_RES_SEARCH_ENTRY:
1329                                 nentries++;
1330                                 print_entry( ld, msg, attrsonly );
1331                                 break;
1332
1333                         case LDAP_RES_SEARCH_REFERENCE:
1334                                 nreferences++;
1335                                 print_reference( ld, msg );
1336                                 break;
1337
1338                         case LDAP_RES_EXTENDED:
1339                                 nextended++;
1340                                 print_extended( ld, msg );
1341
1342                                 if ( ldap_msgid( msg ) == 0 ) {
1343                                         /* unsolicited extended operation */
1344                                         goto done;
1345                                 }
1346
1347                                 if ( cancel_msgid != -1 &&
1348                                                 cancel_msgid == ldap_msgid( msg ) ) {
1349                                         printf(_("Cancelled \n"));
1350                                         printf(_("cancel_msgid = %d\n"), cancel_msgid);
1351                                         goto done;
1352                                 }
1353                                 break;
1354
1355                         case LDAP_RES_SEARCH_RESULT:
1356                                 /* pagedResults stuff is dealt with
1357                                  * in tool_print_ctrls(), called by
1358                                  * print_results(). */
1359                                 rc = print_result( ld, msg, 1 );
1360                                 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1361                                         break;
1362                                 }
1363
1364                                 goto done;
1365
1366                         case LDAP_RES_INTERMEDIATE:
1367                                 npartial++;
1368                                 ldap_parse_intermediate( ld, msg,
1369                                         &retoid, &retdata, NULL, 0 );
1370
1371                                 nresponses_psearch = 0;
1372
1373                                 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1374                                         printf(_("SyncInfo Received\n"));
1375                                         ldap_memfree( retoid );
1376                                         ber_bvfree( retdata );
1377                                         break;
1378                                 }
1379
1380                                 print_partial( ld, msg );
1381                                 ldap_memfree( retoid );
1382                                 ber_bvfree( retdata );
1383                                 goto done;
1384                         }
1385
1386                         if ( ldapsync && sync_slimit != -1 &&
1387                                         nresponses_psearch >= sync_slimit ) {
1388                                 BerElement *msgidber = NULL;
1389                                 struct berval *msgidvalp = NULL;
1390                                 msgidber = ber_alloc_t(LBER_USE_DER);
1391                                 ber_printf(msgidber, "{i}", msgid);
1392                                 ber_flatten(msgidber, &msgidvalp);
1393                                 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1394                                         msgidvalp, NULL, NULL, &cancel_msgid);
1395                                 nresponses_psearch = -1;
1396                         }
1397                 }
1398
1399                 ldap_msgfree( res );
1400         }
1401
1402 done:
1403         if ( rc == -1 ) {
1404                 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1405                 return( rc );
1406         }
1407
1408         ldap_msgfree( res );
1409
1410         if ( pagedResults ) { 
1411                 npagedresponses += nresponses;
1412                 npagedentries += nentries;
1413                 npagedextended += nextended;
1414                 npagedpartial += npartial;
1415                 npagedreferences += nreferences;
1416                 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1417                         printf( _("\n# numResponses: %d\n"), npagedresponses );
1418                         if( npagedentries ) {
1419                                 printf( _("# numEntries: %d\n"), npagedentries );
1420                         }
1421                         if( npagedextended ) {
1422                                 printf( _("# numExtended: %d\n"), npagedextended );
1423                         }
1424                         if( npagedpartial ) {
1425                                 printf( _("# numPartial: %d\n"), npagedpartial );
1426                         }
1427                         if( npagedreferences ) {
1428                                 printf( _("# numReferences: %d\n"), npagedreferences );
1429                         }
1430                 }
1431         } else if ( ldif < 2 ) {
1432                 printf( _("\n# numResponses: %d\n"), nresponses );
1433                 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1434                 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1435                 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1436                 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1437         }
1438
1439         return( rc );
1440 }
1441
1442 /* This is the proposed new way of doing things.
1443  * It is more efficient, but the API is non-standard.
1444  */
1445 static void
1446 print_entry(
1447         LDAP    *ld,
1448         LDAPMessage     *entry,
1449         int             attrsonly)
1450 {
1451         char            *ufn = NULL;
1452         char    tmpfname[ 256 ];
1453         char    url[ 256 ];
1454         int                     i, rc;
1455         BerElement              *ber = NULL;
1456         struct berval           bv, *bvals, **bvp = &bvals;
1457         LDAPControl **ctrls = NULL;
1458         FILE            *tmpfp;
1459
1460         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1461
1462         if ( ldif < 2 ) {
1463                 ufn = ldap_dn2ufn( bv.bv_val );
1464                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1465         }
1466         tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1467
1468         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1469         if( rc != LDAP_SUCCESS ) {
1470                 fprintf(stderr, _("print_entry: %d\n"), rc );
1471                 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1472                 exit( EXIT_FAILURE );
1473         }
1474
1475         if( ctrls ) {
1476                 tool_print_ctrls( ld, ctrls );
1477                 ldap_controls_free( ctrls );
1478         }
1479
1480         if ( includeufn ) {
1481                 if( ufn == NULL ) {
1482                         ufn = ldap_dn2ufn( bv.bv_val );
1483                 }
1484                 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1485         }
1486
1487         if( ufn != NULL ) ldap_memfree( ufn );
1488
1489         if ( attrsonly ) bvp = NULL;
1490
1491         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1492                 rc == LDAP_SUCCESS;
1493                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1494         {
1495                 if (bv.bv_val == NULL) break;
1496
1497                 if ( attrsonly ) {
1498                         tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1499
1500                 } else if ( bvals ) {
1501                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1502                                 if ( vals2tmp > 1 || ( vals2tmp &&
1503                                         ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1504                                 {
1505                                         int tmpfd;
1506                                         /* write value to file */
1507                                         snprintf( tmpfname, sizeof tmpfname,
1508                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1509                                                 tmpdir, bv.bv_val );
1510                                         tmpfp = NULL;
1511
1512                                         tmpfd = mkstemp( tmpfname );
1513
1514                                         if ( tmpfd < 0  ) {
1515                                                 perror( tmpfname );
1516                                                 continue;
1517                                         }
1518
1519                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1520                                                 perror( tmpfname );
1521                                                 continue;
1522                                         }
1523
1524                                         if ( fwrite( bvals[ i ].bv_val,
1525                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1526                                         {
1527                                                 perror( tmpfname );
1528                                                 fclose( tmpfp );
1529                                                 continue;
1530                                         }
1531
1532                                         fclose( tmpfp );
1533
1534                                         snprintf( url, sizeof url, "%s%s", urlpre,
1535                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1536
1537                                         urlize( url );
1538                                         tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1539
1540                                 } else {
1541                                         tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1542                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1543                                 }
1544                         }
1545                         ber_memfree( bvals );
1546                 }
1547         }
1548
1549         if( ber != NULL ) {
1550                 ber_free( ber, 0 );
1551         }
1552 }
1553
1554 static void print_reference(
1555         LDAP *ld,
1556         LDAPMessage *reference )
1557 {
1558         int rc;
1559         char **refs = NULL;
1560         LDAPControl **ctrls;
1561
1562         if( ldif < 2 ) {
1563                 printf(_("# search reference\n"));
1564         }
1565
1566         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1567
1568         if( rc != LDAP_SUCCESS ) {
1569                 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1570                 exit( EXIT_FAILURE );
1571         }
1572
1573         if( refs ) {
1574                 int i;
1575                 for( i=0; refs[i] != NULL; i++ ) {
1576                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1577                                 "ref", refs[i], strlen(refs[i]) );
1578                 }
1579                 ber_memvfree( (void **) refs );
1580         }
1581
1582         if( ctrls ) {
1583                 tool_print_ctrls( ld, ctrls );
1584                 ldap_controls_free( ctrls );
1585         }
1586 }
1587
1588 static void print_extended(
1589         LDAP *ld,
1590         LDAPMessage *extended )
1591 {
1592         int rc;
1593         char *retoid = NULL;
1594         struct berval *retdata = NULL;
1595
1596         if( ldif < 2 ) {
1597                 printf(_("# extended result response\n"));
1598         }
1599
1600         rc = ldap_parse_extended_result( ld, extended,
1601                 &retoid, &retdata, 0 );
1602
1603         if( rc != LDAP_SUCCESS ) {
1604                 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1605                 exit( EXIT_FAILURE );
1606         }
1607
1608         if ( ldif < 2 ) {
1609                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1610                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1611         }
1612         ber_memfree( retoid );
1613
1614         if(retdata) {
1615                 if ( ldif < 2 ) {
1616                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1617                                 "data", retdata->bv_val, retdata->bv_len );
1618                 }
1619                 ber_bvfree( retdata );
1620         }
1621
1622         print_result( ld, extended, 0 );
1623 }
1624
1625 static void print_partial(
1626         LDAP *ld,
1627         LDAPMessage *partial )
1628 {
1629         int rc;
1630         char *retoid = NULL;
1631         struct berval *retdata = NULL;
1632         LDAPControl **ctrls = NULL;
1633
1634         if( ldif < 2 ) {
1635                 printf(_("# extended partial response\n"));
1636         }
1637
1638         rc = ldap_parse_intermediate( ld, partial,
1639                 &retoid, &retdata, &ctrls, 0 );
1640
1641         if( rc != LDAP_SUCCESS ) {
1642                 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1643                 exit( EXIT_FAILURE );
1644         }
1645
1646         if ( ldif < 2 ) {
1647                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1648                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1649         }
1650
1651         ber_memfree( retoid );
1652
1653         if( retdata ) {
1654                 if ( ldif < 2 ) {
1655                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1656                                 "data", retdata->bv_val, retdata->bv_len );
1657                 }
1658
1659                 ber_bvfree( retdata );
1660         }
1661
1662         if( ctrls ) {
1663                 tool_print_ctrls( ld, ctrls );
1664                 ldap_controls_free( ctrls );
1665         }
1666 }
1667
1668 static int print_result(
1669         LDAP *ld,
1670         LDAPMessage *result, int search )
1671 {
1672         int rc;
1673         int err;
1674         char *matcheddn = NULL;
1675         char *text = NULL;
1676         char **refs = NULL;
1677         LDAPControl **ctrls = NULL;
1678
1679         if( search ) {
1680                 if ( ldif < 2 ) {
1681                         printf(_("# search result\n"));
1682                 }
1683                 if ( ldif < 1 ) {
1684                         printf("%s: %d\n", _("search"), ldap_msgid(result) );
1685                 }
1686         }
1687
1688         rc = ldap_parse_result( ld, result,
1689                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1690
1691         if( rc != LDAP_SUCCESS ) {
1692                 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1693                 exit( EXIT_FAILURE );
1694         }
1695
1696
1697         if( !ldif ) {
1698                 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1699
1700         } else if ( err != LDAP_SUCCESS ) {
1701                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1702         }
1703
1704         if( matcheddn ) {
1705                 if( *matcheddn ) {
1706                 if( !ldif ) {
1707                         tool_write_ldif( LDIF_PUT_VALUE,
1708                                 "matchedDN", matcheddn, strlen(matcheddn) );
1709                 } else {
1710                         fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1711                 }
1712                 }
1713
1714                 ber_memfree( matcheddn );
1715         }
1716
1717         if( text ) {
1718                 if( *text ) {
1719                         if( !ldif ) {
1720                                 if ( err == LDAP_PARTIAL_RESULTS ) {
1721                                         char    *line;
1722
1723                                         for ( line = text; line != NULL; ) {
1724                                                 char    *next = strchr( line, '\n' );
1725
1726                                                 tool_write_ldif( LDIF_PUT_TEXT,
1727                                                         "text", line,
1728                                                         next ? (size_t) (next - line) : strlen( line ));
1729
1730                                                 line = next ? next + 1 : NULL;
1731                                         }
1732
1733                                 } else {
1734                                         tool_write_ldif( LDIF_PUT_TEXT, "text",
1735                                                 text, strlen(text) );
1736                                 }
1737                         } else {
1738                                 fprintf( stderr, _("Additional information: %s\n"), text );
1739                         }
1740                 }
1741
1742                 ber_memfree( text );
1743         }
1744
1745         if( refs ) {
1746                 int i;
1747                 for( i=0; refs[i] != NULL; i++ ) {
1748                         if( !ldif ) {
1749                                 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1750                         } else {
1751                                 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1752                         }
1753                 }
1754
1755                 ber_memvfree( (void **) refs );
1756         }
1757
1758         pr_morePagedResults = 0;
1759
1760         if( ctrls ) {
1761                 tool_print_ctrls( ld, ctrls );
1762                 ldap_controls_free( ctrls );
1763         }
1764
1765         return err;
1766 }
1767