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