]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
put 'break' only at the end of the 'case'
[openldap] / clients / tools / ldapsearch.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
4  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
5  */
6
7 #include "portable.h"
8
9 #include <stdio.h>
10
11 #include <ac/stdlib.h>
12
13 #include <ac/ctype.h>
14 #include <ac/signal.h>
15 #include <ac/string.h>
16 #include <ac/unistd.h>
17 #include <ac/errno.h>
18 #include <sys/stat.h>
19
20 #ifdef HAVE_FCNTL_H
21 #include <fcntl.h>
22 #endif
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
25 #endif
26 #ifdef HAVE_IO_H
27 #include <io.h>
28 #endif
29
30 #include <ldap.h>
31
32 #include "ldif.h"
33 #include "lutil.h"
34 #include "lutil_ldap.h"
35 #include "ldap_defaults.h"
36 #include "ldap_log.h"
37
38 static char *def_tmpdir;
39 static char *def_urlpre;
40
41 static void
42 usage( const char *s )
43 {
44         fprintf( stderr,
45 "usage: %s [options] [filter [attributes...]]\nwhere:\n"
46 "  filter\tRFC-2254 compliant LDAP search filter\n"
47 "  attributes\twhitespace-separated list of attribute descriptions\n"
48 "    which may include:\n"
49 "      1.1   no attributes\n"
50 "      *     all user attributes\n"
51 "      +     all operational attributes\n"
52
53 "Search options:\n"
54 "  -a deref   one of never (default), always, search, or find\n"
55 "  -A         retrieve attribute names only (no values)\n"
56 "  -b basedn  base dn for search\n"
57 "  -E [!]<ctrl>[=<ctrlparam>] search controls (! indicates criticality)\n"
58 "             [!]mv=<filter>              (matched values filter)\n"
59 "             [!]pr=<size>                (paged results)\n"
60 #ifdef LDAP_CONTROL_SUBENTRIES
61 "             [!]subentries[=true|false]  (subentries)\n"
62 #endif
63 "  -F prefix  URL prefix for files (default: %s)\n"
64 "  -l limit   time limit (in seconds) for search\n"
65 "  -L         print responses in LDIFv1 format\n"
66 "  -LL        print responses in LDIF format without comments\n"
67 "  -LLL       print responses in LDIF format without comments\n"
68 "             and version\n"
69 "  -s scope   one of base, one, or sub (search scope)\n"
70 "  -S attr    sort the results by attribute `attr'\n"
71 "  -t         write binary values to files in temporary directory\n"
72 "  -tt        write all values to files in temporary directory\n"
73 "  -T path    write files to directory specified by path (default: %s)\n"
74 "  -u         include User Friendly entry names in the output\n"
75 "  -z limit   size limit (in entries) for search\n"
76
77 "Common options:\n"
78 "  -d level   set LDAP debugging level to `level'\n"
79 "  -D binddn  bind DN\n"
80 "  -e [!]<ctrl>[=<ctrlparam>] general controls (! indicates criticality)\n"
81 "             [!]authzid=<authzid> (\"dn:<dn>\" or \"u:<user>\")\n"
82 "             [!]manageDSAit       (alternate form, see -M)\n"
83 "             [!]noop\n"
84 "  -f file    read operations from `file'\n"
85 "  -h host    LDAP server\n"
86 "  -H URI     LDAP Uniform Resource Indentifier(s)\n"
87 "  -I         use SASL Interactive mode\n"
88 "  -k         use Kerberos authentication\n"
89 "  -K         like -k, but do only step 1 of the Kerberos bind\n"
90 "  -M         enable Manage DSA IT control (-MM to make critical)\n"
91 "  -n         show what would be done but don't actually search\n"
92 "  -O props   SASL security properties\n"
93 "  -p port    port on LDAP server\n"
94 "  -P version procotol version (default: 3)\n"
95 "  -Q         use SASL Quiet mode\n"
96 "  -R realm   SASL realm\n"
97 "  -U authcid SASL authentication identity\n"
98 "  -v         run in verbose mode (diagnostics to standard output)\n"
99 "  -w passwd  bind passwd (for simple authentication)\n"
100 "  -W         prompt for bind passwd\n"
101 "  -x         Simple authentication\n"
102 "  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
103 "  -y file    Read passwd from file\n"
104 "  -Y mech    SASL mechanism\n"
105 "  -Z         Start TLS request (-ZZ to require successful response)\n"
106 , s, def_urlpre, def_tmpdir );
107
108         exit( EXIT_FAILURE );
109 }
110
111 static void print_entry LDAP_P((
112         LDAP    *ld,
113         LDAPMessage     *entry,
114         int             attrsonly));
115
116 static void print_reference(
117         LDAP *ld,
118         LDAPMessage *reference );
119
120 static void print_extended(
121         LDAP *ld,
122         LDAPMessage *extended );
123
124 static void print_partial(
125         LDAP *ld,
126         LDAPMessage *partial );
127
128 static int print_result(
129         LDAP *ld,
130         LDAPMessage *result,
131         int search );
132
133 static void print_ctrls(
134         LDAPControl **ctrls );
135
136 static int write_ldif LDAP_P((
137         int type,
138         char *name,
139         char *value,
140         ber_len_t vallen ));
141
142 static int dosearch LDAP_P((
143         LDAP    *ld,
144         char    *base,
145         int             scope,
146         char    *filtpatt,
147         char    *value,
148         char    **attrs,
149         int             attrsonly,
150         LDAPControl **sctrls,
151         LDAPControl **cctrls,
152         struct timeval *timeout,
153         int     sizelimit ));
154
155 static char *tmpdir = NULL;
156 static char *urlpre = NULL;
157 static char *prog = NULL;
158 static char     *binddn = NULL;
159 static struct berval passwd = { 0, NULL };
160 static char     *base = NULL;
161 static char     *ldaphost = NULL;
162 static char *ldapuri = NULL;
163 static int      ldapport = 0;
164 #ifdef HAVE_CYRUS_SASL
165 static unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
166 static char     *sasl_realm = NULL;
167 static char     *sasl_authc_id = NULL;
168 static char     *sasl_authz_id = NULL;
169 static char     *sasl_mech = NULL;
170 static char     *sasl_secprops = NULL;
171 #endif
172 static int      use_tls = 0;
173 static char     *sortattr = NULL;
174 static int      verbose, not, includeufn, vals2tmp, ldif;
175
176 static int pagedResults = 0;
177 static ber_int_t pageSize = 0;
178 static ber_int_t entriesLeft = 0;
179 static ber_int_t morePagedResults = 1;
180 static struct berval cookie = { 0, NULL };
181 static int npagedresponses;
182 static int npagedentries;
183 static int npagedreferences;
184 static int npagedextended;
185 static int npagedpartial;
186
187 static int parse_page_control(
188         LDAP *ld,
189         LDAPMessage *result,
190         struct berval *cookie );
191
192 static void
193 urlize(char *url)
194 {
195         char *p;
196
197         if (*LDAP_DIRSEP != '/') {
198                 for (p = url; *p; p++) {
199                         if (*p == *LDAP_DIRSEP)
200                                 *p = '/';
201                 }
202         }
203 }
204
205 int
206 main( int argc, char **argv )
207 {
208         char            *infile, *filtpattern, **attrs = NULL, line[BUFSIZ];
209         FILE            *fp = NULL;
210         int                     rc, i, first, scope, deref, attrsonly, manageDSAit, noop, crit;
211         int                     referrals, timelimit, sizelimit, debug;
212         int             authmethod, version, want_bindpw;
213         LDAP            *ld = NULL;
214         BerElement      *ber = NULL;
215         char    *control = NULL, *cvalue;
216         int             subentries, valuesReturnFilter;
217         struct berval   *sebvalp = NULL, *vrbvalp = NULL;
218         char    *vrFilter  = NULL;
219         char    *pw_file = NULL;
220         char    *authzid = NULL;
221         struct berval   *prbvalp = NULL;
222
223         infile = NULL;
224         debug = verbose = not = vals2tmp = referrals =
225                 subentries = valuesReturnFilter =
226                 attrsonly = manageDSAit = noop = ldif = want_bindpw = 0;
227
228         npagedresponses = npagedentries = npagedreferences =
229                 npagedextended = npagedpartial = 0;
230
231         prog = lutil_progname( "ldapsearch", argc, argv );
232
233         lutil_log_initialize(argc, argv);
234
235         deref = sizelimit = timelimit = version = -1;
236
237         scope = LDAP_SCOPE_SUBTREE;
238         authmethod = -1;
239
240         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
241            (def_tmpdir = getenv("TMP")) == NULL &&
242            (def_tmpdir = getenv("TEMP")) == NULL )
243         {
244                 def_tmpdir = LDAP_TMPDIR;
245         }
246
247         if ( !*def_tmpdir )
248                 def_tmpdir = LDAP_TMPDIR;
249
250         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
251
252         if( def_urlpre == NULL ) {
253                 perror( "malloc" );
254                 return EXIT_FAILURE;
255         }
256
257         sprintf( def_urlpre, "file:///%s/",
258                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
259
260         urlize( def_urlpre );
261
262         while (( i = getopt( argc, argv, "Aa:b:E:F:f:Ll:S:s:T:tuz:"
263                 "Cd:e:D:h:H:IkKMnO:p:P:QR:U:vw:WxX:y:Y:Z")) != EOF )
264         {
265         switch( i ) {
266         /* Search Options */
267         case 'a':       /* set alias deref option */
268                 if ( strcasecmp( optarg, "never" ) == 0 ) {
269                 deref = LDAP_DEREF_NEVER;
270                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
271                 deref = LDAP_DEREF_SEARCHING;
272                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
273                 deref = LDAP_DEREF_FINDING;
274                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
275                 deref = LDAP_DEREF_ALWAYS;
276                 } else {
277                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
278                 usage(prog);
279                 }
280                 break;
281         case 'A':       /* retrieve attribute names only -- no values */
282                 ++attrsonly;
283                 break;
284         case 'b': /* search base */
285                 base = strdup( optarg );
286                 break;
287         case 'E': /* search controls */
288                 if( version == LDAP_VERSION2 ) {
289                         fprintf( stderr, "%s: -E incompatible with LDAPv%d\n",
290                                 prog, version );
291                         return EXIT_FAILURE;
292                 }
293
294                 /* should be extended to support comma separated list of
295                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
296                  */
297
298                 crit = 0;
299                 cvalue = NULL;
300                 if( optarg[0] == '!' ) {
301                         crit = 1;
302                         optarg++;
303                 }
304
305                 control = strdup( optarg );
306                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
307                         *cvalue++ = '\0';
308                 }
309
310                 if ( strcasecmp( control, "mv" ) == 0 ) {
311                         /* ValuesReturnFilter control */
312                         if( valuesReturnFilter ) {
313                                 fprintf( stderr, "ValuesReturnFilter previously specified\n");
314                                 return EXIT_FAILURE;
315                         }
316                         valuesReturnFilter= 1 + crit;
317
318                         if ( cvalue == NULL ) {
319                                 fprintf( stderr,
320                                         "missing filter in ValuesReturnFilter control\n");
321                                 return EXIT_FAILURE;
322                         }
323
324                         vrFilter = cvalue;
325                         version = LDAP_VERSION3;
326
327                 } else if ( strcasecmp( control, "pr" ) == 0 ) {
328                         int num, tmp;
329                         /* PagedResults control */
330                         if ( pagedResults != 0 ) {
331                                 fprintf( stderr, "PagedResultsControl previously specified\n" );
332                                 return EXIT_FAILURE;
333                         }
334                         
335                         num = sscanf( cvalue, "%d", &tmp );
336                         if ( num != 1 ) {
337                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", cvalue);
338                                 return EXIT_FAILURE;
339
340                         }
341                         pageSize = (ber_int_t) tmp;
342                         pagedResults = 1 + crit;
343
344 #ifdef LDAP_CONTROL_SUBENTRIES
345                 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
346                         if( subentries ) {
347                                 fprintf( stderr, "subentries control previously specified\n");
348                                 return EXIT_FAILURE;
349                         }
350                         if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
351                                 subentries = 2;
352                         } else if ( strcasecmp( cvalue, "false") == 0 ) {
353                                 subentries = 1;
354                         } else {
355                                 fprintf( stderr,
356                                         "subentries control value \"%s\" invalid\n");
357                                 return EXIT_FAILURE;
358                         }
359                         if( crit ) subentries *= -1;
360 #endif
361
362                 } else {
363                         fprintf( stderr, "Invalid control name: %s\n", control );
364                         usage(prog);
365                         return EXIT_FAILURE;
366                 }
367                 break;
368
369         case 'f':       /* input file */
370                 if( infile != NULL ) {
371                         fprintf( stderr, "%s: -f previously specified\n", prog );
372                         return EXIT_FAILURE;
373                 }
374                 infile = strdup( optarg );
375                 break;
376         case 'F':       /* uri prefix */
377                 if( urlpre ) free( urlpre );
378                 urlpre = strdup( optarg );
379                 break;
380         case 'l':       /* time limit */
381                 timelimit = atoi( optarg );
382                 if( timelimit < 0 ) {
383                         fprintf( stderr, "%s: invalid timelimit (%d) specified\n",
384                                 prog, timelimit );
385                         return EXIT_FAILURE;
386                 }
387                 break;
388         case 'L':       /* print entries in LDIF format */
389                 ++ldif;
390                 break;
391         case 's':       /* search scope */
392                 if ( strcasecmp( optarg, "base" ) == 0 ) {
393                 scope = LDAP_SCOPE_BASE;
394                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
395                 scope = LDAP_SCOPE_ONELEVEL;
396                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
397                 scope = LDAP_SCOPE_SUBTREE;
398                 } else {
399                 fprintf( stderr, "scope should be base, one, or sub\n" );
400                 usage(prog);
401                 }
402                 break;
403         case 'S':       /* sort attribute */
404                 sortattr = strdup( optarg );
405                 break;
406         case 'u':       /* include UFN */
407                 ++includeufn;
408                 break;
409         case 't':       /* write attribute values to TMPDIR files */
410                 ++vals2tmp;
411                 break;
412         case 'T':       /* tmpdir */
413                 if( tmpdir ) free( tmpdir );
414                 tmpdir = strdup( optarg );
415                 break;
416         case 'z':       /* size limit */
417                 sizelimit = atoi( optarg );
418                 break;
419
420         /* Common Options */
421         case 'C':
422                 referrals++;
423                 break;
424         case 'd':
425             debug |= atoi( optarg );
426             break;
427         case 'D':       /* bind DN */
428                 if( binddn != NULL ) {
429                         fprintf( stderr, "%s: -D previously specified\n", prog );
430                         return EXIT_FAILURE;
431                 }
432             binddn = strdup( optarg );
433             break;
434         case 'e': /* general controls */
435                 if( version == LDAP_VERSION2 ) {
436                         fprintf( stderr, "%s: -e incompatible with LDAPv%d\n",
437                                 prog, version );
438                         return EXIT_FAILURE;
439                 }
440
441                 /* should be extended to support comma separated list of
442                  *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
443                  */
444
445                 crit = 0;
446                 cvalue = NULL;
447                 if( optarg[0] == '!' ) {
448                         crit = 1;
449                         optarg++;
450                 }
451
452                 control = strdup( optarg );
453                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
454                         *cvalue++ = '\0';
455                 }
456
457                 if ( strcasecmp( control, "authzid" ) == 0 ) {
458                         if( authzid != NULL ) {
459                                 fprintf( stderr, "authzid control previously specified");
460                                 return EXIT_FAILURE;
461                         }
462                         if( cvalue == NULL ) {
463                                 fprintf( stderr, "authzid: control value expected" );
464                                 usage(prog);
465                                 return EXIT_FAILURE;
466                         }
467                         if( !crit ) {
468                                 fprintf( stderr, "authzid: must be marked critical" );
469                                 usage(prog);
470                                 return EXIT_FAILURE;
471                         }
472
473                         assert( authzid == NULL );
474                         authzid = control;
475                         break;
476                         
477                 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
478                         if( manageDSAit ) {
479                                 fprintf( stderr, "manageDSAit control previously specified");
480                                 return EXIT_FAILURE;
481                         }
482                         if( cvalue != NULL ) {
483                                 fprintf( stderr, "manageDSAit: no control value expected" );
484                                 usage(prog);
485                                 return EXIT_FAILURE;
486                         }
487
488                         manageDSAit = 1 + crit;
489                         break;
490                         
491                 } else if ( strcasecmp( control, "noop" ) == 0 ) {
492                         if( noop ) {
493                                 fprintf( stderr, "noop control previously specified");
494                                 return EXIT_FAILURE;
495                         }
496                         if( cvalue != NULL ) {
497                                 fprintf( stderr, "noop: no control value expected" );
498                                 usage(prog);
499                                 return EXIT_FAILURE;
500                         }
501
502                         noop = 1 + crit;
503                         break;
504
505                 } else {
506                         fprintf( stderr, "Invalid general control name: %s\n", control );
507                         usage(prog);
508                         return EXIT_FAILURE;
509                 }
510         case 'h':       /* ldap host */
511                 if( ldapuri != NULL ) {
512                         fprintf( stderr, "%s: -h incompatible with -H\n", prog );
513                         return EXIT_FAILURE;
514                 }
515                 if( ldaphost != NULL ) {
516                         fprintf( stderr, "%s: -h previously specified\n", prog );
517                         return EXIT_FAILURE;
518                 }
519             ldaphost = strdup( optarg );
520             break;
521         case 'H':       /* ldap URI */
522                 if( ldaphost != NULL ) {
523                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
524                         return EXIT_FAILURE;
525                 }
526                 if( ldapport ) {
527                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
528                         return EXIT_FAILURE;
529                 }
530                 if( ldapuri != NULL ) {
531                         fprintf( stderr, "%s: -H previously specified\n", prog );
532                         return EXIT_FAILURE;
533                 }
534             ldapuri = strdup( optarg );
535             break;
536         case 'I':
537 #ifdef HAVE_CYRUS_SASL
538                 if( version == LDAP_VERSION2 ) {
539                         fprintf( stderr, "%s: -I incompatible with version %d\n",
540                                 prog, version );
541                         return EXIT_FAILURE;
542                 }
543                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
544                         fprintf( stderr, "%s: incompatible previous "
545                                 "authentication choice\n",
546                                 prog );
547                         return EXIT_FAILURE;
548                 }
549                 authmethod = LDAP_AUTH_SASL;
550                 version = LDAP_VERSION3;
551                 sasl_flags = LDAP_SASL_INTERACTIVE;
552                 break;
553 #else
554                 fprintf( stderr, "%s: was not compiled with SASL support\n",
555                         prog );
556                 return( EXIT_FAILURE );
557 #endif
558         case 'k':       /* kerberos bind */
559 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
560                 if( version > LDAP_VERSION2 ) {
561                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
562                                 prog, version );
563                         return EXIT_FAILURE;
564                 }
565
566                 if( authmethod != -1 ) {
567                         fprintf( stderr, "%s: -k incompatible with previous "
568                                 "authentication choice\n", prog );
569                         return EXIT_FAILURE;
570                 }
571                         
572                 authmethod = LDAP_AUTH_KRBV4;
573 #else
574                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
575                 return EXIT_FAILURE;
576 #endif
577             break;
578         case 'K':       /* kerberos bind, part one only */
579 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
580                 if( version > LDAP_VERSION2 ) {
581                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
582                                 prog, version );
583                         return EXIT_FAILURE;
584                 }
585                 if( authmethod != -1 ) {
586                         fprintf( stderr, "%s: incompatible with previous "
587                                 "authentication choice\n", prog );
588                         return EXIT_FAILURE;
589                 }
590
591                 authmethod = LDAP_AUTH_KRBV41;
592 #else
593                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
594                 return( EXIT_FAILURE );
595 #endif
596             break;
597         case 'M':
598                 /* enable Manage DSA IT */
599                 if( version == LDAP_VERSION2 ) {
600                         fprintf( stderr, "%s: -M incompatible with LDAPv%d\n",
601                                 prog, version );
602                         return EXIT_FAILURE;
603                 }
604                 manageDSAit++;
605                 version = LDAP_VERSION3;
606                 break;
607         case 'n':       /* print deletes, don't actually do them */
608             ++not;
609             break;
610         case 'O':
611 #ifdef HAVE_CYRUS_SASL
612                 if( sasl_secprops != NULL ) {
613                         fprintf( stderr, "%s: -O previously specified\n", prog );
614                         return EXIT_FAILURE;
615                 }
616                 if( version == LDAP_VERSION2 ) {
617                         fprintf( stderr, "%s: -O incompatible with LDAPv%d\n",
618                                 prog, version );
619                         return EXIT_FAILURE;
620                 }
621                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
622                         fprintf( stderr, "%s: incompatible previous "
623                                 "authentication choice\n", prog );
624                         return EXIT_FAILURE;
625                 }
626                 authmethod = LDAP_AUTH_SASL;
627                 version = LDAP_VERSION3;
628                 sasl_secprops = strdup( optarg );
629 #else
630                 fprintf( stderr, "%s: not compiled with SASL support\n",
631                         prog );
632                 return( EXIT_FAILURE );
633 #endif
634                 break;
635         case 'p':
636                 if( ldapport ) {
637                         fprintf( stderr, "%s: -p previously specified\n", prog );
638                         return EXIT_FAILURE;
639                 }
640             ldapport = atoi( optarg );
641             break;
642         case 'P':
643                 switch( atoi(optarg) ) {
644                 case 2:
645                         if( version == LDAP_VERSION3 ) {
646                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
647                                         prog, version );
648                                 return EXIT_FAILURE;
649                         }
650                         version = LDAP_VERSION2;
651                         break;
652                 case 3:
653                         if( version == LDAP_VERSION2 ) {
654                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
655                                         prog, version );
656                                 return EXIT_FAILURE;
657                         }
658                         version = LDAP_VERSION3;
659                         break;
660                 default:
661                         fprintf( stderr, "%s: protocol version should be 2 or 3\n",
662                                 prog );
663                         usage( prog );
664                         return( EXIT_FAILURE );
665                 } break;
666         case 'Q':
667 #ifdef HAVE_CYRUS_SASL
668                 if( version == LDAP_VERSION2 ) {
669                         fprintf( stderr, "%s: -Q incompatible with version %d\n",
670                                 prog, version );
671                         return EXIT_FAILURE;
672                 }
673                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
674                         fprintf( stderr, "%s: incompatible previous "
675                                 "authentication choice\n",
676                                 prog );
677                         return EXIT_FAILURE;
678                 }
679                 authmethod = LDAP_AUTH_SASL;
680                 version = LDAP_VERSION3;
681                 sasl_flags = LDAP_SASL_QUIET;
682                 break;
683 #else
684                 fprintf( stderr, "%s: not compiled with SASL support\n",
685                         prog );
686                 return( EXIT_FAILURE );
687 #endif
688         case 'R':
689 #ifdef HAVE_CYRUS_SASL
690                 if( sasl_realm != NULL ) {
691                         fprintf( stderr, "%s: -R previously specified\n", prog );
692                         return EXIT_FAILURE;
693                 }
694                 if( version == LDAP_VERSION2 ) {
695                         fprintf( stderr, "%s: -R incompatible with version %d\n",
696                                 prog, version );
697                         return EXIT_FAILURE;
698                 }
699                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
700                         fprintf( stderr, "%s: incompatible previous "
701                                 "authentication choice\n",
702                                 prog );
703                         return EXIT_FAILURE;
704                 }
705                 authmethod = LDAP_AUTH_SASL;
706                 version = LDAP_VERSION3;
707                 sasl_realm = strdup( optarg );
708 #else
709                 fprintf( stderr, "%s: not compiled with SASL support\n",
710                         prog );
711                 return( EXIT_FAILURE );
712 #endif
713                 break;
714         case 'U':
715 #ifdef HAVE_CYRUS_SASL
716                 if( sasl_authc_id != NULL ) {
717                         fprintf( stderr, "%s: -U previously specified\n", prog );
718                         return EXIT_FAILURE;
719                 }
720                 if( version == LDAP_VERSION2 ) {
721                         fprintf( stderr, "%s: -U incompatible with version %d\n",
722                                 prog, version );
723                         return EXIT_FAILURE;
724                 }
725                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
726                         fprintf( stderr, "%s: incompatible previous "
727                                 "authentication choice\n",
728                                 prog );
729                         return EXIT_FAILURE;
730                 }
731                 authmethod = LDAP_AUTH_SASL;
732                 version = LDAP_VERSION3;
733                 sasl_authc_id = strdup( optarg );
734 #else
735                 fprintf( stderr, "%s: not compiled with SASL support\n",
736                         prog );
737                 return( EXIT_FAILURE );
738 #endif
739                 break;
740         case 'v':       /* verbose mode */
741             verbose++;
742             break;
743         case 'w':       /* password */
744             passwd.bv_val = strdup( optarg );
745                 {
746                         char* p;
747
748                         for( p = optarg; *p != '\0'; p++ ) {
749                                 *p = '\0';
750                         }
751                 }
752                 passwd.bv_len = strlen( passwd.bv_val );
753             break;
754         case 'W':
755                 want_bindpw++;
756                 break;
757         case 'y':
758                 pw_file = optarg;
759                 break;
760         case 'Y':
761 #ifdef HAVE_CYRUS_SASL
762                 if( sasl_mech != NULL ) {
763                         fprintf( stderr, "%s: -Y previously specified\n", prog );
764                         return EXIT_FAILURE;
765                 }
766                 if( version == LDAP_VERSION2 ) {
767                         fprintf( stderr, "%s: -Y incompatible with version %d\n",
768                                 prog, version );
769                         return EXIT_FAILURE;
770                 }
771                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
772                         fprintf( stderr, "%s: incompatible with authentication choice\n", prog );
773                         return EXIT_FAILURE;
774                 }
775                 authmethod = LDAP_AUTH_SASL;
776                 version = LDAP_VERSION3;
777                 sasl_mech = strdup( optarg );
778 #else
779                 fprintf( stderr, "%s: not compiled with SASL support\n",
780                         prog );
781                 return( EXIT_FAILURE );
782 #endif
783                 break;
784         case 'x':
785                 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
786                         fprintf( stderr, "%s: incompatible with previous "
787                                 "authentication choice\n", prog );
788                         return EXIT_FAILURE;
789                 }
790                 authmethod = LDAP_AUTH_SIMPLE;
791                 break;
792         case 'X':
793 #ifdef HAVE_CYRUS_SASL
794                 if( sasl_authz_id != NULL ) {
795                         fprintf( stderr, "%s: -X previously specified\n", prog );
796                         return EXIT_FAILURE;
797                 }
798                 if( version == LDAP_VERSION2 ) {
799                         fprintf( stderr, "%s: -X incompatible with LDAPv%d\n",
800                                 prog, version );
801                         return EXIT_FAILURE;
802                 }
803                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
804                         fprintf( stderr, "%s: -X incompatible with "
805                                 "authentication choice\n", prog );
806                         return EXIT_FAILURE;
807                 }
808                 authmethod = LDAP_AUTH_SASL;
809                 version = LDAP_VERSION3;
810                 sasl_authz_id = strdup( optarg );
811 #else
812                 fprintf( stderr, "%s: not compiled with SASL support\n",
813                         prog );
814                 return( EXIT_FAILURE );
815 #endif
816                 break;
817         case 'Z':
818 #ifdef HAVE_TLS
819                 if( version == LDAP_VERSION2 ) {
820                         fprintf( stderr, "%s: -Z incompatible with version %d\n",
821                                 prog, version );
822                         return EXIT_FAILURE;
823                 }
824                 version = LDAP_VERSION3;
825                 use_tls++;
826 #else
827                 fprintf( stderr, "%s: not compiled with TLS support\n",
828                         prog );
829                 return( EXIT_FAILURE );
830 #endif
831                 break;
832         default:
833                 fprintf( stderr, "%s: unrecognized option -%c\n",
834                         prog, optopt );
835                 usage(prog);
836         }
837         }
838
839         if (version == -1) {
840                 version = LDAP_VERSION3;
841         }
842         if (authmethod == -1 && version > LDAP_VERSION2) {
843 #ifdef HAVE_CYRUS_SASL
844                 authmethod = LDAP_AUTH_SASL;
845 #else
846                 authmethod = LDAP_AUTH_SIMPLE;
847 #endif
848         }
849
850         if (( argc - optind < 1 ) ||
851                 ( *argv[optind] != '(' /*')'*/ &&
852                 ( strchr( argv[optind], '=' ) == NULL ) ) )
853         {
854                 filtpattern = "(objectclass=*)";
855         } else {
856                 filtpattern = strdup( argv[optind++] );
857         }
858
859         if ( argv[optind] != NULL ) {
860                 attrs = &argv[optind];
861         }
862
863         if ( infile != NULL ) {
864                 if ( infile[0] == '-' && infile[1] == '\0' ) {
865                         fp = stdin;
866                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
867                         perror( infile );
868                         return EXIT_FAILURE;
869                 }
870         }
871
872         if ( tmpdir == NULL ) {
873                 tmpdir = def_tmpdir;
874
875                 if ( urlpre == NULL )
876                         urlpre = def_urlpre;
877         }
878
879         if( urlpre == NULL ) {
880                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
881
882                 if( urlpre == NULL ) {
883                         perror( "malloc" );
884                         return EXIT_FAILURE;
885                 }
886
887                 sprintf( urlpre, "file:///%s/",
888                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
889
890                 urlize( urlpre );
891         }
892
893         if ( debug ) {
894                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
895                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
896                 }
897                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
898                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
899                 }
900                 ldif_debug = debug;
901         }
902
903 #ifdef SIGPIPE
904         (void) SIGNAL( SIGPIPE, SIG_IGN );
905 #endif
906
907         if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
908                 if ( verbose ) {
909                         fprintf( stderr, "ldap_init( %s, %d )\n",
910                                 ldaphost != NULL ? ldaphost : "<DEFAULT>",
911                                 ldapport );
912                 }
913
914                 ld = ldap_init( ldaphost, ldapport );
915                 if( ld == NULL ) {
916                         perror("ldapsearch: ldap_init");
917                         return EXIT_FAILURE;
918                 }
919
920         } else {
921                 if ( verbose ) {
922                         fprintf( stderr, "ldap_initialize( %s )\n",
923                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
924                 }
925
926                 rc = ldap_initialize( &ld, ldapuri );
927                 if( rc != LDAP_SUCCESS ) {
928                         fprintf( stderr, "Could not create LDAP session handle (%d): %s\n",
929                                 rc, ldap_err2string(rc) );
930                         return EXIT_FAILURE;
931                 }
932         }
933
934         if (deref != -1 &&
935                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
936         {
937                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
938                 return EXIT_FAILURE;
939         }
940         if (timelimit != -1 &&
941                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
942         {
943                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
944                 return EXIT_FAILURE;
945         }
946         if (sizelimit != -1 &&
947                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
948         {
949                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
950                 return EXIT_FAILURE;
951         }
952
953         /* referrals */
954         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
955                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
956         {
957                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
958                         referrals ? "on" : "off" );
959                 return EXIT_FAILURE;
960         }
961
962         if (version == -1 ) {
963                 version = LDAP_VERSION3;
964         }
965
966         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
967                 != LDAP_OPT_SUCCESS )
968         {
969                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
970                         version );
971                 return EXIT_FAILURE;
972         }
973
974         if ( use_tls && ( ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS )) {
975                 ldap_perror( ld, "ldap_start_tls" );
976                 if ( use_tls > 1 ) {
977                         return EXIT_FAILURE;
978                 }
979         }
980
981         if ( pw_file || want_bindpw ) {
982                 if ( pw_file ) {
983                         rc = lutil_get_filed_password( pw_file, &passwd );
984                         if( rc ) return EXIT_FAILURE;
985                 } else {
986                         passwd.bv_val = getpassphrase( "Enter LDAP Password: " );
987                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
988                 }
989         }
990
991         if ( authmethod == LDAP_AUTH_SASL ) {
992 #ifdef HAVE_CYRUS_SASL
993                 void *defaults;
994
995                 if( sasl_secprops != NULL ) {
996                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
997                                 (void *) sasl_secprops );
998                         
999                         if( rc != LDAP_OPT_SUCCESS ) {
1000                                 fprintf( stderr,
1001                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1002                                         sasl_secprops );
1003                                 return( EXIT_FAILURE );
1004                         }
1005                 }
1006                 
1007                 defaults = lutil_sasl_defaults( ld,
1008                         sasl_mech,
1009                         sasl_realm,
1010                         sasl_authc_id,
1011                         passwd.bv_val,
1012                         sasl_authz_id );
1013
1014                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
1015                         sasl_mech, NULL, NULL,
1016                         sasl_flags, lutil_sasl_interact, defaults );
1017
1018                 if( rc != LDAP_SUCCESS ) {
1019                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
1020                         return( EXIT_FAILURE );
1021                 }
1022 #else
1023                 fprintf( stderr, "%s: not compiled with SASL support\n",
1024                         prog);
1025                 return( EXIT_FAILURE );
1026 #endif
1027         } else {
1028                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
1029                                 != LDAP_SUCCESS ) {
1030                         ldap_perror( ld, "ldap_bind" );
1031                         return( EXIT_FAILURE );
1032                 }
1033         }
1034
1035 getNextPage:
1036         if ( manageDSAit || noop || subentries
1037                 || valuesReturnFilter || pageSize )
1038         {
1039                 int err;
1040                 int i=0;
1041                 int crit = 0;
1042                 LDAPControl c[6];
1043                 LDAPControl *ctrls[7];
1044                 
1045                 if ( authzid ) {
1046                         c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1047                         c[i].ldctl_value.bv_val = authzid;
1048                         c[i].ldctl_value.bv_len = strlen( authzid );
1049                         c[i].ldctl_iscritical = 1;
1050
1051                         if( c[i].ldctl_iscritical ) crit++;
1052                         ctrls[i] = &c[i];
1053                         ctrls[++i] = NULL;
1054                 }
1055
1056                 if ( manageDSAit ) {
1057                         c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1058                         c[i].ldctl_value.bv_val = NULL;
1059                         c[i].ldctl_value.bv_len = 0;
1060                         c[i].ldctl_iscritical = manageDSAit > 1;
1061
1062                         if( c[i].ldctl_iscritical ) crit++;
1063                         ctrls[i] = &c[i];
1064                         ctrls[++i] = NULL;
1065                 }
1066
1067                 if ( noop ) {
1068                         c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1069                         c[i].ldctl_value.bv_val = NULL;
1070                         c[i].ldctl_value.bv_len = 0;
1071                         c[i].ldctl_iscritical = noop > 1;
1072
1073                         if( c[i].ldctl_iscritical ) crit++;
1074                         ctrls[i] = &c[i];
1075                         ctrls[++i] = NULL;
1076                 }
1077
1078 #ifdef LDAP_CONTROL_SUBENTRIES
1079                 if ( subentries ) {
1080                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1081                                 return EXIT_FAILURE;
1082                         }
1083
1084                         err = ber_printf( ber, "{b}", abs(subentries) == 1 ? 0 : 1 );
1085                 if ( err == LBER_ERROR ) {
1086                                 ber_free( ber, 1 );
1087                                 fprintf( stderr, "Subentries control encoding error!\n" );
1088                                 return EXIT_FAILURE;
1089                         }
1090
1091                         if ( ber_flatten( ber, &sebvalp ) == LBER_ERROR ) {
1092                                 return EXIT_FAILURE;
1093                         }
1094
1095                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
1096                         c[i].ldctl_value=(*sebvalp);
1097                         c[i].ldctl_iscritical = subentries < 1;
1098
1099                         if( c[i].ldctl_iscritical ) crit++;
1100                         ctrls[i] = &c[i];
1101                         ctrls[++i] = NULL;
1102                 }
1103 #endif
1104
1105                 if ( valuesReturnFilter ) {
1106                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1107                                 return EXIT_FAILURE;
1108                         }
1109
1110                 if ( ( err = ldap_put_vrFilter( ber, vrFilter ) ) == -1 ) {
1111                                 ber_free( ber, 1 );
1112                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
1113                                 return EXIT_FAILURE;
1114                         }
1115
1116                         if ( ber_flatten( ber, &vrbvalp ) == LBER_ERROR ) {
1117                                 return EXIT_FAILURE;
1118                         }
1119
1120                         ber_free( ber, 1 );
1121
1122                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
1123                         c[i].ldctl_value=(*vrbvalp);
1124                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
1125
1126                         if( c[i].ldctl_iscritical ) crit++;
1127                         ctrls[i] = &c[i];
1128                         ctrls[++i] = NULL;
1129                 }
1130
1131                 if ( pagedResults ) {
1132                         if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
1133                                 return EXIT_FAILURE;
1134                         }
1135
1136                         ber_printf( ber, "{iO}", pageSize, &cookie );
1137                         if ( ber_flatten( ber, &prbvalp ) == LBER_ERROR ) {
1138                                 return EXIT_FAILURE;
1139                         }
1140                         
1141                         ber_free( ber, 1 );
1142
1143                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
1144                         c[i].ldctl_value=(*prbvalp);
1145                         c[i].ldctl_iscritical = pagedResults > 1;
1146
1147                         if( c[i].ldctl_iscritical ) crit++;
1148                         ctrls[i] = &c[i];
1149                         ctrls[++i] = NULL;
1150                 }
1151
1152                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1153
1154                 if( err != LDAP_OPT_SUCCESS ) {
1155                         fprintf( stderr, "Could not set %scontrols\n",
1156                                 crit ? "critical " : "" );
1157                         if( crit ) {
1158                                 return EXIT_FAILURE;
1159                         }
1160                 }
1161
1162                 ber_bvfree( sebvalp );
1163                 ber_bvfree( vrbvalp );
1164                 ber_bvfree( prbvalp );
1165         }
1166         
1167         if ( verbose ) {
1168                 fprintf( stderr, "filter%s: %s\nrequesting: ",
1169                         infile != NULL ? " pattern" : "",
1170                         filtpattern );
1171
1172                 if ( attrs == NULL ) {
1173                         fprintf( stderr, "ALL" );
1174                 } else {
1175                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1176                                 fprintf( stderr, "%s ", attrs[ i ] );
1177                         }
1178                 }
1179                 fprintf( stderr, "\n" );
1180         }
1181
1182         if ( ldif == 0 ) {
1183                 printf( "# extended LDIF\n" );
1184         } else if ( ldif < 3 ) {
1185                 printf( "version: %d\n\n", 1 );
1186         }
1187
1188         if (ldif < 2 ) {
1189                 printf( "#\n"
1190                         "# LDAPv%d\n"
1191                         "# base <%s> with scope %s\n"
1192                         "# filter%s: %s\n"
1193                         "# requesting: ",
1194                         version,
1195                         base, (scope == LDAP_SCOPE_BASE) ? "base"
1196                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
1197                         infile != NULL ? " pattern" : "",
1198                         filtpattern );
1199
1200                 if ( attrs == NULL ) {
1201                         printf( "ALL" );
1202                 } else {
1203                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
1204                                 printf( "%s ", attrs[ i ] );
1205                         }
1206                 }
1207
1208                 if ( manageDSAit ) {
1209                         printf("\n# with manageDSAit %scontrol",
1210                                 manageDSAit > 1 ? "critical " : "" );
1211                 }
1212                 if ( noop ) {
1213                         printf("\n# with noop %scontrol",
1214                                 noop > 1 ? "critical " : "" );
1215                 }
1216                 if ( subentries ) {
1217                         printf("\n# with subentries %scontrol: %s",
1218                                 subentries < 0 ? "critical " : "",
1219                                 abs(subentries) == 1 ? "false" : "true" );
1220                 }
1221                 if ( valuesReturnFilter ) {
1222                         printf("\n# with valuesReturnFilter %scontrol: %s",
1223                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
1224                 }
1225                 if ( pageSize ) {
1226                         printf("\n# with pagedResults %scontrol: size=%d",
1227                                 (pagedResults > 1) ? "critical " : "", 
1228                                 pageSize );
1229                 }
1230
1231                 printf( "\n#\n\n" );
1232         }
1233
1234         if ( infile == NULL ) {
1235                 rc = dosearch( ld, base, scope, NULL, filtpattern,
1236                         attrs, attrsonly, NULL, NULL, NULL, -1 );
1237
1238         } else {
1239                 rc = 0;
1240                 first = 1;
1241                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
1242                         line[ strlen( line ) - 1 ] = '\0';
1243                         if ( !first ) {
1244                                 putchar( '\n' );
1245                         } else {
1246                                 first = 0;
1247                         }
1248                         rc = dosearch( ld, base, scope, filtpattern, line,
1249                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
1250                 }
1251                 if ( fp != stdin ) {
1252                         fclose( fp );
1253                 }
1254         }
1255
1256         if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) { 
1257                 char    buf[6];
1258                 int     i, moreEntries, tmpSize;
1259
1260                 /* Loop to get the next pages when 
1261                  * enter is pressed on the terminal.
1262                  */
1263                 if ( entriesLeft > 0 ) {
1264                         printf( "Estimate entries: %d\n", entriesLeft );
1265                 }
1266                 printf( "Press [size] Enter for the next {%d|size} entries.\n",
1267                         (int)pageSize ); 
1268                 i = 0;
1269                 moreEntries = getchar();
1270                 while ( moreEntries != EOF && moreEntries != '\n' ) { 
1271                         if ( i < sizeof(buf) - 1 ) {
1272                                 buf[i] = moreEntries;
1273                                 i++;
1274                         }
1275                         moreEntries = getchar();
1276                 }
1277                 buf[i] = '\0';
1278
1279                 if ( i > 0 && isdigit( buf[0] ) ) {
1280                         int num = sscanf( buf, "%d", &tmpSize );
1281                         if ( num != 1 ) {
1282                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
1283                                 return EXIT_FAILURE;
1284
1285                         }
1286                         pageSize = (ber_int_t)tmpSize;
1287                 }
1288
1289                 goto getNextPage;       
1290         }
1291
1292         ldap_unbind( ld );
1293         return( rc );
1294 }
1295
1296
1297 static int dosearch(
1298         LDAP    *ld,
1299         char    *base,
1300         int             scope,
1301         char    *filtpatt,
1302         char    *value,
1303         char    **attrs,
1304         int             attrsonly,
1305         LDAPControl **sctrls,
1306         LDAPControl **cctrls,
1307         struct timeval *timeout,
1308         int sizelimit )
1309 {
1310         char                    *filter;
1311         int                     rc;
1312         int                     nresponses;
1313         int                     nentries;
1314         int                     nreferences;
1315         int                     nextended;
1316         int                     npartial;
1317         LDAPMessage             *res, *msg;
1318         ber_int_t       msgid;
1319
1320         if( filtpatt != NULL ) {
1321                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1322                 if( filter == NULL ) {
1323                         perror( "malloc" );
1324                         return EXIT_FAILURE;
1325                 }
1326
1327                 sprintf( filter, filtpatt, value );
1328
1329                 if ( verbose ) {
1330                         fprintf( stderr, "filter: %s\n", filter );
1331                 }
1332
1333                 if( ldif < 2 ) {
1334                         printf( "#\n# filter: %s\n#\n", filter );
1335                 }
1336
1337         } else {
1338                 filter = value;
1339         }
1340
1341         if ( not ) {
1342                 return LDAP_SUCCESS;
1343         }
1344
1345         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1346                 sctrls, cctrls, timeout, sizelimit, &msgid );
1347
1348         if ( filtpatt != NULL ) {
1349                 free( filter );
1350         }
1351
1352         if( rc != LDAP_SUCCESS ) {
1353                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
1354                         prog, ldap_err2string( rc ), rc );
1355                 return( rc );
1356         }
1357
1358         nresponses = nentries = nreferences = nextended = npartial = 0;
1359
1360         res = NULL;
1361
1362         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1363                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1364                 NULL, &res )) > 0 )
1365         {
1366                 if( sortattr ) {
1367                         (void) ldap_sort_entries( ld, &res,
1368                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1369                 }
1370
1371                 for ( msg = ldap_first_message( ld, res );
1372                         msg != NULL;
1373                         msg = ldap_next_message( ld, msg ) )
1374                 {
1375                         if( nresponses++ ) putchar('\n');
1376
1377                         switch( ldap_msgtype( msg ) ) {
1378                         case LDAP_RES_SEARCH_ENTRY:
1379                                 nentries++;
1380                                 print_entry( ld, msg, attrsonly );
1381                                 break;
1382
1383                         case LDAP_RES_SEARCH_REFERENCE:
1384                                 nreferences++;
1385                                 print_reference( ld, msg );
1386                                 break;
1387
1388                         case LDAP_RES_EXTENDED:
1389                                 nextended++;
1390                                 print_extended( ld, msg );
1391
1392                                 if( ldap_msgid( msg ) == 0 ) {
1393                                         /* unsolicited extended operation */
1394                                         goto done;
1395                                 }
1396                                 break;
1397
1398                         case LDAP_RES_EXTENDED_PARTIAL:
1399                                 npartial++;
1400                                 print_partial( ld, msg );
1401                                 break;
1402
1403                         case LDAP_RES_SEARCH_RESULT:
1404                                 rc = print_result( ld, msg, 1 );
1405                                 if ( pageSize != 0 ) { 
1406                                         rc = parse_page_control( ld, msg, &cookie );
1407                                 }
1408                                 goto done;
1409                         }
1410                 }
1411
1412                 ldap_msgfree( res );
1413         }
1414
1415         if ( rc == -1 ) {
1416                 ldap_perror( ld, "ldap_result" );
1417                 return( rc );
1418         }
1419
1420 done:
1421         if ( pageSize != 0 ) { 
1422                 npagedresponses = npagedresponses + nresponses;
1423                 npagedentries = npagedentries + nentries;
1424                 npagedreferences = npagedreferences + nreferences;
1425                 npagedextended = npagedextended + nextended;
1426                 npagedpartial = npagedpartial + npartial;
1427                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1428                         printf( "\n# numResponses: %d\n", npagedresponses );
1429                         if( nentries ) printf( "# numEntries: %d\n", npagedentries );
1430                         if( nextended ) printf( "# numExtended: %d\n", npagedextended );
1431                         if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
1432                         if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
1433                 }
1434         } else if ( ldif < 2 ) {
1435                 printf( "\n# numResponses: %d\n", nresponses );
1436                 if( nentries ) printf( "# numEntries: %d\n", nentries );
1437                 if( nextended ) printf( "# numExtended: %d\n", nextended );
1438                 if( npartial ) printf( "# numPartial: %d\n", npartial );
1439                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
1440         }
1441
1442         return( rc );
1443 }
1444
1445 #if 1
1446 /* This is the original version, the old way of doing things. */
1447 static void
1448 print_entry(
1449         LDAP    *ld,
1450         LDAPMessage     *entry,
1451         int             attrsonly)
1452 {
1453         char            *a, *dn, *ufn;
1454         char    tmpfname[ 256 ];
1455         char    url[ 256 ];
1456         int                     i, rc;
1457         BerElement              *ber = NULL;
1458         struct berval   **bvals;
1459         LDAPControl **ctrls = NULL;
1460         FILE            *tmpfp;
1461
1462         dn = ldap_get_dn( ld, entry );
1463         ufn = NULL;
1464
1465         if ( ldif < 2 ) {
1466                 ufn = ldap_dn2ufn( dn );
1467                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1468         }
1469         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1470
1471         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1472
1473         if( rc != LDAP_SUCCESS ) {
1474                 fprintf(stderr, "print_entry: %d\n", rc );
1475                 ldap_perror( ld, "ldap_get_entry_controls" );
1476                 exit( EXIT_FAILURE );
1477         }
1478
1479         if( ctrls ) {
1480                 print_ctrls( ctrls );
1481                 ldap_controls_free( ctrls );
1482         }
1483
1484         if ( includeufn ) {
1485                 if( ufn == NULL ) {
1486                         ufn = ldap_dn2ufn( dn );
1487                 }
1488                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1489         }
1490
1491         if( ufn != NULL ) ldap_memfree( ufn );
1492         ldap_memfree( dn );
1493
1494         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1495                 a = ldap_next_attribute( ld, entry, ber ) )
1496         {
1497                 if ( attrsonly ) {
1498                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1499
1500                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1501                         for ( i = 0; bvals[i] != NULL; i++ ) {
1502                                 if ( vals2tmp > 1 || ( vals2tmp
1503                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1504                                 {
1505                                         int tmpfd;
1506                                         /* write value to file */
1507                                         snprintf( tmpfname, sizeof tmpfname,
1508                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1509                                                 tmpdir, a );
1510                                         tmpfp = NULL;
1511
1512                                         tmpfd = mkstemp( tmpfname );
1513
1514                                         if ( tmpfd < 0  ) {
1515                                                 perror( tmpfname );
1516                                                 continue;
1517                                         }
1518
1519                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1520                                                 perror( tmpfname );
1521                                                 continue;
1522                                         }
1523
1524                                         if ( fwrite( bvals[ i ]->bv_val,
1525                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1526                                         {
1527                                                 perror( tmpfname );
1528                                                 fclose( tmpfp );
1529                                                 continue;
1530                                         }
1531
1532                                         fclose( tmpfp );
1533
1534                                         snprintf( url, sizeof url, "%s%s", urlpre,
1535                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1536
1537                                         urlize( url );
1538                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1539
1540                                 } else {
1541                                         write_ldif( LDIF_PUT_VALUE, a,
1542                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1543                                 }
1544                         }
1545                         ber_bvecfree( bvals );
1546                 }
1547         }
1548
1549         if( ber != NULL ) {
1550                 ber_free( ber, 0 );
1551         }
1552 }
1553 #else
1554 /* This is the proposed new way of doing things.
1555  * It is more efficient, but the API is non-standard.
1556  */
1557 static void
1558 print_entry(
1559         LDAP    *ld,
1560         LDAPMessage     *entry,
1561         int             attrsonly)
1562 {
1563         char            *ufn = NULL;
1564         char    tmpfname[ 256 ];
1565         char    url[ 256 ];
1566         int                     i, rc;
1567         BerElement              *ber = NULL;
1568         struct berval           bv, *bvals, **bvp = &bvals;
1569         LDAPControl **ctrls = NULL;
1570         FILE            *tmpfp;
1571
1572         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1573
1574         if ( ldif < 2 ) {
1575                 ufn = ldap_dn2ufn( bv.bv_val );
1576                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1577         }
1578         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1579
1580         rc = ldap_int_get_controls( ber, &ctrls );
1581
1582         if( rc != LDAP_SUCCESS ) {
1583                 fprintf(stderr, "print_entry: %d\n", rc );
1584                 ldap_perror( ld, "ldap_get_entry_controls" );
1585                 exit( EXIT_FAILURE );
1586         }
1587
1588         if( ctrls ) {
1589                 print_ctrls( ctrls );
1590                 ldap_controls_free( ctrls );
1591         }
1592
1593         if ( includeufn ) {
1594                 if( ufn == NULL ) {
1595                         ufn = ldap_dn2ufn( bv.bv_val );
1596                 }
1597                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1598         }
1599
1600         if( ufn != NULL ) ldap_memfree( ufn );
1601
1602         if ( attrsonly ) bvp = NULL;
1603
1604         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1605                 rc == LDAP_SUCCESS;
1606                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1607         {
1608                 if (bv.bv_val == NULL) break;
1609
1610                 if ( attrsonly ) {
1611                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1612
1613                 } else {
1614                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1615                                 if ( vals2tmp > 1 || ( vals2tmp
1616                                         && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
1617                                 {
1618                                         int tmpfd;
1619                                         /* write value to file */
1620                                         snprintf( tmpfname, sizeof tmpfname,
1621                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1622                                                 tmpdir, bv.bv_val );
1623                                         tmpfp = NULL;
1624
1625                                         tmpfd = mkstemp( tmpfname );
1626
1627                                         if ( tmpfd < 0  ) {
1628                                                 perror( tmpfname );
1629                                                 continue;
1630                                         }
1631
1632                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1633                                                 perror( tmpfname );
1634                                                 continue;
1635                                         }
1636
1637                                         if ( fwrite( bvals[ i ].bv_val,
1638                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1639                                         {
1640                                                 perror( tmpfname );
1641                                                 fclose( tmpfp );
1642                                                 continue;
1643                                         }
1644
1645                                         fclose( tmpfp );
1646
1647                                         snprintf( url, sizeof url, "%s%s", urlpre,
1648                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1649
1650                                         urlize( url );
1651                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1652
1653                                 } else {
1654                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1655                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1656                                 }
1657                         }
1658                         ber_memfree( bvals );
1659                 }
1660         }
1661
1662         if( ber != NULL ) {
1663                 ber_free( ber, 0 );
1664         }
1665 }
1666 #endif
1667
1668 static void print_reference(
1669         LDAP *ld,
1670         LDAPMessage *reference )
1671 {
1672         int rc;
1673         char **refs = NULL;
1674         LDAPControl **ctrls;
1675
1676         if( ldif < 2 ) {
1677                 printf("# search reference\n");
1678         }
1679
1680         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1681
1682         if( rc != LDAP_SUCCESS ) {
1683                 ldap_perror(ld, "ldap_parse_reference");
1684                 exit( EXIT_FAILURE );
1685         }
1686
1687         if( refs ) {
1688                 int i;
1689                 for( i=0; refs[i] != NULL; i++ ) {
1690                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1691                                 "ref", refs[i], strlen(refs[i]) );
1692                 }
1693                 ber_memvfree( (void **) refs );
1694         }
1695
1696         if( ctrls ) {
1697                 print_ctrls( ctrls );
1698                 ldap_controls_free( ctrls );
1699         }
1700 }
1701
1702 static void print_extended(
1703         LDAP *ld,
1704         LDAPMessage *extended )
1705 {
1706         int rc;
1707         char *retoid = NULL;
1708         struct berval *retdata = NULL;
1709
1710         if( ldif < 2 ) {
1711                 printf("# extended result response\n");
1712         }
1713
1714         rc = ldap_parse_extended_result( ld, extended,
1715                 &retoid, &retdata, 0 );
1716
1717         if( rc != LDAP_SUCCESS ) {
1718                 ldap_perror(ld, "ldap_parse_extended_result");
1719                 exit( EXIT_FAILURE );
1720         }
1721
1722         if ( ldif < 2 ) {
1723                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1724                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1725         }
1726         ber_memfree( retoid );
1727
1728         if(retdata) {
1729                 if ( ldif < 2 ) {
1730                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1731                                 "data", retdata->bv_val, retdata->bv_len );
1732                 }
1733                 ber_bvfree( retdata );
1734         }
1735
1736         print_result( ld, extended, 0 );
1737 }
1738
1739 static void print_partial(
1740         LDAP *ld,
1741         LDAPMessage *partial )
1742 {
1743         int rc;
1744         char *retoid = NULL;
1745         struct berval *retdata = NULL;
1746         LDAPControl **ctrls = NULL;
1747
1748         if( ldif < 2 ) {
1749                 printf("# extended partial response\n");
1750         }
1751
1752         rc = ldap_parse_extended_partial( ld, partial,
1753                 &retoid, &retdata, &ctrls, 0 );
1754
1755         if( rc != LDAP_SUCCESS ) {
1756                 ldap_perror(ld, "ldap_parse_extended_partial");
1757                 exit( EXIT_FAILURE );
1758         }
1759
1760         if ( ldif < 2 ) {
1761                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1762                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1763         }
1764
1765         ber_memfree( retoid );
1766
1767         if( retdata ) {
1768                 if ( ldif < 2 ) {
1769                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1770                                 "data", retdata->bv_val, retdata->bv_len );
1771                 }
1772
1773                 ber_bvfree( retdata );
1774         }
1775
1776         if( ctrls ) {
1777                 print_ctrls( ctrls );
1778                 ldap_controls_free( ctrls );
1779         }
1780 }
1781
1782 static int print_result(
1783         LDAP *ld,
1784         LDAPMessage *result, int search )
1785 {
1786         int rc;
1787         int err;
1788         char *matcheddn = NULL;
1789         char *text = NULL;
1790         char **refs = NULL;
1791         LDAPControl **ctrls = NULL;
1792
1793         if( search ) {
1794                 if ( ldif < 2 ) {
1795                         printf("# search result\n");
1796                 }
1797                 if ( ldif < 1 ) {
1798                         printf("%s: %d\n", "search", ldap_msgid(result) );
1799                 }
1800         }
1801
1802         rc = ldap_parse_result( ld, result,
1803                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1804
1805         if( rc != LDAP_SUCCESS ) {
1806                 ldap_perror(ld, "ldap_parse_result");
1807                 exit( EXIT_FAILURE );
1808         }
1809
1810
1811         if( !ldif ) {
1812                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1813
1814         } else if ( err != LDAP_SUCCESS ) {
1815                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1816         }
1817
1818         if( matcheddn && *matcheddn ) {
1819                 if( !ldif ) {
1820                         write_ldif( LDIF_PUT_VALUE,
1821                                 "matchedDN", matcheddn, strlen(matcheddn) );
1822                 } else {
1823                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1824                 }
1825
1826                 ber_memfree( matcheddn );
1827         }
1828
1829         if( text && *text ) {
1830                 if( !ldif ) {
1831                         write_ldif( LDIF_PUT_TEXT, "text",
1832                                 text, strlen(text) );
1833                 } else {
1834                         fprintf( stderr, "Additional information: %s\n", text );
1835                 }
1836
1837                 ber_memfree( text );
1838         }
1839
1840         if( refs ) {
1841                 int i;
1842                 for( i=0; refs[i] != NULL; i++ ) {
1843                         if( !ldif ) {
1844                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1845                         } else {
1846                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1847                         }
1848                 }
1849
1850                 ber_memvfree( (void **) refs );
1851         }
1852
1853         if( ctrls ) {
1854                 print_ctrls( ctrls );
1855                 ldap_controls_free( ctrls );
1856         }
1857
1858         return err;
1859 }
1860
1861 static void print_ctrls(
1862         LDAPControl **ctrls )
1863 {
1864         int i;
1865         for(i=0; ctrls[i] != NULL; i++ ) {
1866                 /* control: OID criticality base64value */
1867                 struct berval *b64 = NULL;
1868                 ber_len_t len;
1869                 char *str;
1870
1871                 len = ldif ? 2 : 0;
1872                 len += strlen( ctrls[i]->ldctl_oid );
1873
1874                 /* add enough for space after OID and the critical value itself */
1875                 len += ctrls[i]->ldctl_iscritical
1876                         ? sizeof("true") : sizeof("false");
1877
1878                 /* convert to base64 */
1879                 if( ctrls[i]->ldctl_value.bv_len ) {
1880                         b64 = ber_memalloc( sizeof(struct berval) );
1881                         
1882                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1883                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1884                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1885
1886                         b64->bv_len = lutil_b64_ntop(
1887                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1888                                 b64->bv_val, b64->bv_len );
1889                 }
1890
1891                 if( b64 ) {
1892                         len += 1 + b64->bv_len;
1893                 }
1894
1895                 str = malloc( len + 1 );
1896                 if ( ldif ) {
1897                         strcpy( str, ": " );
1898                 } else {
1899                         str[0] = '\0';
1900                 }
1901                 strcat( str, ctrls[i]->ldctl_oid );
1902                 strcat( str, ctrls[i]->ldctl_iscritical
1903                         ? " true" : " false" );
1904
1905                 if( b64 ) {
1906                         strcat(str, " ");
1907                         strcat(str, b64->bv_val );
1908                 }
1909
1910                 if ( ldif < 2 ) {
1911                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1912                                 "control", str, len );
1913                 }
1914
1915                 free( str );
1916                 ber_bvfree( b64 );
1917         }
1918 }
1919
1920 static int
1921 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1922 {
1923         char    *ldif;
1924
1925         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1926                 return( -1 );
1927         }
1928
1929         fputs( ldif, stdout );
1930         ber_memfree( ldif );
1931
1932         return( 0 );
1933 }
1934
1935
1936 static int 
1937 parse_page_control(
1938         LDAP *ld,
1939         LDAPMessage *result,
1940         struct berval *cookie )
1941 {
1942         int rc;
1943         int err;
1944         LDAPControl **ctrl = NULL;
1945         LDAPControl *ctrlp = NULL;
1946         BerElement *ber;
1947         ber_tag_t tag;
1948         struct berval servercookie = { 0, NULL };
1949
1950
1951         rc = ldap_parse_result( ld, result,
1952                 &err, NULL, NULL, NULL, &ctrl, 0 );
1953
1954         if( rc != LDAP_SUCCESS ) {
1955                 ldap_perror(ld, "ldap_parse_result");
1956                 exit( EXIT_FAILURE );
1957         }
1958
1959         if ( err != LDAP_SUCCESS ) {
1960                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1961         }
1962
1963         if( ctrl ) {
1964                 /* Parse the control value
1965                  * searchResult ::= SEQUENCE {
1966                  *              size    INTEGER (0..maxInt),
1967                  *                              -- result set size estimate from server - unused
1968                  *              cookie  OCTET STRING
1969                  */
1970                 ctrlp = *ctrl;
1971                 ber = ber_init( &ctrlp->ldctl_value );
1972                 if ( ber == NULL ) {
1973                         fprintf( stderr, "Internal error.\n" );
1974                         return EXIT_FAILURE;
1975                 }
1976
1977                 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1978                 ber_dupbv( cookie, &servercookie );
1979                 (void) ber_free( ber, 1 );
1980
1981                 if( tag == LBER_ERROR ) {
1982                         fprintf( stderr, "Paged results response control could not be decoded.\n" );
1983                         return EXIT_FAILURE;
1984                 }
1985
1986                 if( entriesLeft < 0 ) {
1987                         fprintf( stderr, "Invalid entries estimate in paged results response.\n" );
1988                         return EXIT_FAILURE;
1989                 }
1990
1991
1992                 ldap_controls_free( ctrl );
1993         } else {
1994                 morePagedResults = 0;
1995         }
1996
1997         return err;
1998 }