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