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