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