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