]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Clean up usage()
[openldap] / clients / tools / ldapsearch.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2000 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
37 static void
38 usage( const char *s )
39 {
40         fprintf( stderr,
41 "usage: %s [options] [filter [attributes...]]\nwhere:\n"
42 "  filter\tRFC-2254 compliant LDAP search filter\n"
43 "  attributes\twhitespace-separated list of attribute descriptions\n"
44 "    which may include:\n"
45 "      1.1   no attributes\n"
46 "      *     all user attributes\n"
47 "      +     all operational attributes\n"
48
49 "Search options:\n"
50 "  -a deref   one of never (default), always, search, or find\n"
51 "  -A         retrieve attribute names only (no values)\n"
52 "  -b basedn  base dn for search\n"
53 "  -l limit   time limit (in seconds) for search\n"
54 "  -L         print responses in LDIFv1 format\n"
55 "  -LL        print responses in LDIF format without comments\n"
56 "  -LLL       print responses in LDIF format without comments\n"
57 "             and version\n"
58 "  -s scope   one of base, one, or sub (search scope)\n"
59 "  -S attr    sort the results by attribute `attr'\n"
60 "  -t         write binary values to files in temporary directory\n"
61 "  -tt        write all values to files in temporary directory\n"
62 "  -T path    write files to directory specified by path (default:\n"
63 "             " LDAP_TMPDIR ")\n"
64 "  -u         include User Friendly entry names in the output\n"
65 "  -V prefix  URL prefix for files (default: \"" LDAP_FILE_URI_PREFIX ")\n"
66 "  -z limit   size limit (in entries) for search\n"
67
68 "Common options:\n"
69 "  -d level   set LDAP debugging level to `level'\n"
70 "  -D binddn  bind DN\n"
71 "  -f file    read operations from `file'\n"
72 "  -h host    LDAP server\n"
73 "  -I         use SASL Interactive mode\n"
74 "  -k         use Kerberos authentication\n"
75 "  -K         like -k, but do only step 1 of the Kerberos bind\n"
76 "  -M         enable Manage DSA IT control (-MM to make critical)\n"
77 "  -n         show what would be done but don't actually search\n"
78 "  -O props   SASL security properties\n"
79 "  -p port    port on LDAP server\n"
80 "  -P version procotol version (default: 3)\n"
81 "  -Q         use SASL Quiet mode\n"
82 "  -R realm   SASL realm\n"
83 "  -U user    SASL authentication identity (username)\n"
84 "  -v         run in verbose mode (diagnostics to standard output)\n"
85 "  -w passwd  bind passwd (for simple authentication)\n"
86 "  -W         prompt for bind passwd\n"
87 "  -x         Simple authentication\n"
88 "  -X id      SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
89 "  -Y mech    SASL mechanism\n"
90 "  -Z         Start TLS request (-ZZ to require successful response)\n"
91 , s );
92
93         exit( EXIT_FAILURE );
94 }
95
96 static void print_entry LDAP_P((
97         LDAP    *ld,
98         LDAPMessage     *entry,
99         int             attrsonly));
100
101 static void print_reference(
102         LDAP *ld,
103         LDAPMessage *reference );
104
105 static void print_extended(
106         LDAP *ld,
107         LDAPMessage *extended );
108
109 static void print_partial(
110         LDAP *ld,
111         LDAPMessage *partial );
112
113 static int print_result(
114         LDAP *ld,
115         LDAPMessage *result,
116         int search );
117
118 static void print_ctrls(
119         LDAPControl **ctrls );
120
121 static int write_ldif LDAP_P((
122         int type,
123         char *name,
124         char *value,
125         ber_len_t vallen ));
126
127 static int dosearch LDAP_P((
128         LDAP    *ld,
129         char    *base,
130         int             scope,
131         char    *filtpatt,
132         char    *value,
133         char    **attrs,
134         int             attrsonly,
135         LDAPControl **sctrls,
136         LDAPControl **cctrls,
137         struct timeval *timelimit,
138         int     sizelimit ));
139
140 static char *tmpdir = NULL;
141 static char *urlpre = NULL;
142
143 static char *prog = NULL;
144 static char     *binddn = NULL;
145 static struct berval passwd = { 0, NULL };
146 static char     *base = NULL;
147 static char     *ldaphost = NULL;
148 static int      ldapport = 0;
149 #ifdef HAVE_CYRUS_SASL
150 static unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
151 static char     *sasl_realm = NULL;
152 static char     *sasl_authc_id = NULL;
153 static char     *sasl_authz_id = NULL;
154 static char     *sasl_mech = NULL;
155 static char     *sasl_secprops = NULL;
156 #endif
157 static int      use_tls = 0;
158 static char     *sortattr = NULL;
159 static int      verbose, not, includeufn, vals2tmp, ldif;
160
161 int
162 main( int argc, char **argv )
163 {
164         char            *infile, *filtpattern, **attrs, line[BUFSIZ];
165         FILE            *fp = NULL;
166         int                     rc, i, first, scope, deref, attrsonly, manageDSAit;
167         int                     referrals, timelimit, sizelimit, debug;
168         int             authmethod, version, want_bindpw;
169         LDAP            *ld;
170
171         infile = NULL;
172         debug = verbose = not = vals2tmp = referrals =
173                 attrsonly = manageDSAit = ldif = want_bindpw = 0;
174
175         deref = sizelimit = timelimit = version = -1;
176
177         scope = LDAP_SCOPE_SUBTREE;
178         authmethod = -1;
179
180     prog = (prog = strrchr(argv[0], *LDAP_DIRSEP)) == NULL ? argv[0] : ++prog;
181
182         while (( i = getopt( argc, argv,
183                 "Aa:b:f:Ll:S:s:T:tuV:z:" "Cd:D:h:IkKMnO:p:P:QRU:vw:WxX:Y:Z")) != EOF )
184         {
185         switch( i ) {
186         /* Search Options */
187         case 'a':       /* set alias deref option */
188                 if ( strcasecmp( optarg, "never" ) == 0 ) {
189                 deref = LDAP_DEREF_NEVER;
190                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
191                 deref = LDAP_DEREF_SEARCHING;
192                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
193                 deref = LDAP_DEREF_FINDING;
194                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
195                 deref = LDAP_DEREF_ALWAYS;
196                 } else {
197                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
198                 usage( argv[ 0 ] );
199                 }
200                 break;
201         case 'A':       /* retrieve attribute names only -- no values */
202                 ++attrsonly;
203                 break;
204         case 'b': /* search base */
205                 base = strdup( optarg );
206                 break;
207         case 'f':       /* input file */
208                 if( infile != NULL ) {
209                         fprintf( stderr, "%s: -f previously specified\n" );
210                         return EXIT_FAILURE;
211                 }
212                 infile = strdup( optarg );
213                 break;
214         case 'l':       /* time limit */
215                 timelimit = atoi( optarg );
216                 break;
217         case 'L':       /* print entries in LDIF format */
218                 ++ldif;
219                 break;
220         case 's':       /* search scope */
221                 if ( strcasecmp( optarg, "base" ) == 0 ) {
222                 scope = LDAP_SCOPE_BASE;
223                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
224                 scope = LDAP_SCOPE_ONELEVEL;
225                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
226                 scope = LDAP_SCOPE_SUBTREE;
227                 } else {
228                 fprintf( stderr, "scope should be base, one, or sub\n" );
229                 usage( argv[ 0 ] );
230                 }
231                 break;
232         case 'S':       /* sort attribute */
233                 sortattr = strdup( optarg );
234                 break;
235         case 'u':       /* include UFN */
236                 ++includeufn;
237                 break;
238         case 't':       /* write attribute values to TMPDIR files */
239                 ++vals2tmp;
240                 break;
241         case 'T':       /* tmpdir */
242                 if( tmpdir ) free( tmpdir );
243                 tmpdir = strdup( optarg );
244                 break;
245         case 'V':       /* uri prefix */
246                 if( urlpre ) free( urlpre );
247                 urlpre = strdup( optarg );
248                 break;
249         case 'z':       /* size limit */
250                 sizelimit = atoi( optarg );
251                 break;
252
253         /* Common Options */
254         case 'C':
255                 referrals++;
256                 break;
257         case 'd':
258             debug |= atoi( optarg );
259             break;
260         case 'D':       /* bind DN */
261                 if( binddn != NULL ) {
262                         fprintf( stderr, "%s: -D previously specified\n" );
263                         return EXIT_FAILURE;
264                 }
265             binddn = strdup( optarg );
266             break;
267         case 'h':       /* ldap host */
268                 if( ldaphost != NULL ) {
269                         fprintf( stderr, "%s: -h previously specified\n" );
270                         return EXIT_FAILURE;
271                 }
272             ldaphost = strdup( optarg );
273             break;
274         case 'I':
275 #ifdef HAVE_CYRUS_SASL
276                 if( version == LDAP_VERSION2 ) {
277                         fprintf( stderr, "%s: -I incompatible with version %d\n",
278                                 prog, version );
279                         return EXIT_FAILURE;
280                 }
281                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
282                         fprintf( stderr, "%s: incompatible previous "
283                                 "authentication choice\n",
284                                 prog );
285                         return EXIT_FAILURE;
286                 }
287                 authmethod = LDAP_AUTH_SASL;
288                 version = LDAP_VERSION3;
289                 sasl_flags = LDAP_SASL_INTERACTIVE;
290                 break;
291 #else
292                 fprintf( stderr, "%s: was not compiled with SASL support\n",
293                         prog );
294                 return( EXIT_FAILURE );
295 #endif
296         case 'k':       /* kerberos bind */
297 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
298                 if( version > LDAP_VERSION2 ) {
299                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
300                                 prog, version );
301                         return EXIT_FAILURE;
302                 }
303
304                 if( authmethod != -1 ) {
305                         fprintf( stderr, "%s: -k incompatible with previous "
306                                 "authentication choice\n", prog );
307                         return EXIT_FAILURE;
308                 }
309                         
310                 authmethod = LDAP_AUTH_KRBV4;
311 #else
312                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
313                 return EXIT_FAILURE;
314 #endif
315             break;
316         case 'K':       /* kerberos bind, part one only */
317 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
318                 if( version > LDAP_VERSION2 ) {
319                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
320                                 prog, version );
321                         return EXIT_FAILURE;
322                 }
323                 if( authmethod != -1 ) {
324                         fprintf( stderr, "%s: incompatible with previous "
325                                 "authentication choice\n", prog );
326                         return EXIT_FAILURE;
327                 }
328
329                 authmethod = LDAP_AUTH_KRBV41;
330 #else
331                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
332                 return( EXIT_FAILURE );
333 #endif
334             break;
335         case 'M':
336                 /* enable Manage DSA IT */
337                 if( version == LDAP_VERSION2 ) {
338                         fprintf( stderr, "%s: -M incompatible with LDAPv%d\n",
339                                 prog, version );
340                         return EXIT_FAILURE;
341                 }
342                 manageDSAit++;
343                 version = LDAP_VERSION3;
344                 break;
345         case 'n':       /* print deletes, don't actually do them */
346             ++not;
347             break;
348         case 'O':
349 #ifdef HAVE_CYRUS_SASL
350                 if( sasl_secprops != NULL ) {
351                         fprintf( stderr, "%s: -O previously specified\n" );
352                         return EXIT_FAILURE;
353                 }
354                 if( version == LDAP_VERSION2 ) {
355                         fprintf( stderr, "%s: -O incompatible with LDAPv%d\n",
356                                 prog, version );
357                         return EXIT_FAILURE;
358                 }
359                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
360                         fprintf( stderr, "%s: incompatible previous "
361                                 "authentication choice\n", prog );
362                         return EXIT_FAILURE;
363                 }
364                 authmethod = LDAP_AUTH_SASL;
365                 version = LDAP_VERSION3;
366                 sasl_secprops = strdup( optarg );
367 #else
368                 fprintf( stderr, "%s: not compiled with SASL support\n",
369                         prog );
370                 return( EXIT_FAILURE );
371 #endif
372                 break;
373         case 'p':
374                 if( ldapport ) {
375                         fprintf( stderr, "%s: -p previously specified\n" );
376                         return EXIT_FAILURE;
377                 }
378             ldapport = atoi( optarg );
379             break;
380         case 'P':
381                 switch( atoi(optarg) ) {
382                 case 2:
383                         if( version == LDAP_VERSION3 ) {
384                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
385                                         prog, version );
386                                 return EXIT_FAILURE;
387                         }
388                         version = LDAP_VERSION2;
389                         break;
390                 case 3:
391                         if( version == LDAP_VERSION2 ) {
392                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
393                                         prog, version );
394                                 return EXIT_FAILURE;
395                         }
396                         version = LDAP_VERSION3;
397                         break;
398                 default:
399                         fprintf( stderr, "%s: protocol version should be 2 or 3\n",
400                                 prog );
401                         usage( prog );
402                         return( EXIT_FAILURE );
403                 } break;
404         case 'Q':
405 #ifdef HAVE_CYRUS_SASL
406                 if( version == LDAP_VERSION2 ) {
407                         fprintf( stderr, "%s: -Q incompatible with version %d\n",
408                                 prog, version );
409                         return EXIT_FAILURE;
410                 }
411                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
412                         fprintf( stderr, "%s: incompatible previous "
413                                 "authentication choice\n",
414                                 prog );
415                         return EXIT_FAILURE;
416                 }
417                 authmethod = LDAP_AUTH_SASL;
418                 version = LDAP_VERSION3;
419                 sasl_flags = LDAP_SASL_QUIET;
420                 break;
421 #else
422                 fprintf( stderr, "%s: not compiled with SASL support\n",
423                         prog );
424                 return( EXIT_FAILURE );
425 #endif
426         case 'R':
427 #ifdef HAVE_CYRUS_SASL
428                 if( sasl_realm != NULL ) {
429                         fprintf( stderr, "%s: -R previously specified\n" );
430                         return EXIT_FAILURE;
431                 }
432                 if( version == LDAP_VERSION2 ) {
433                         fprintf( stderr, "%s: -R incompatible with version %d\n",
434                                 prog, version );
435                         return EXIT_FAILURE;
436                 }
437                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
438                         fprintf( stderr, "%s: incompatible previous "
439                                 "authentication choice\n",
440                                 prog );
441                         return EXIT_FAILURE;
442                 }
443                 authmethod = LDAP_AUTH_SASL;
444                 version = LDAP_VERSION3;
445                 sasl_realm = strdup( optarg );
446 #else
447                 fprintf( stderr, "%s: not compiled with SASL support\n",
448                         prog );
449                 return( EXIT_FAILURE );
450 #endif
451                 break;
452         case 'U':
453 #ifdef HAVE_CYRUS_SASL
454                 if( sasl_authc_id != NULL ) {
455                         fprintf( stderr, "%s: -U previously specified\n" );
456                         return EXIT_FAILURE;
457                 }
458                 if( version == LDAP_VERSION2 ) {
459                         fprintf( stderr, "%s: -U incompatible with version %d\n",
460                                 prog, version );
461                         return EXIT_FAILURE;
462                 }
463                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
464                         fprintf( stderr, "%s: incompatible previous "
465                                 "authentication choice\n",
466                                 prog );
467                         return EXIT_FAILURE;
468                 }
469                 authmethod = LDAP_AUTH_SASL;
470                 version = LDAP_VERSION3;
471                 sasl_authc_id = strdup( optarg );
472 #else
473                 fprintf( stderr, "%s: not compiled with SASL support\n",
474                         prog );
475                 return( EXIT_FAILURE );
476 #endif
477                 break;
478         case 'v':       /* verbose mode */
479             verbose++;
480             break;
481         case 'w':       /* password */
482             passwd.bv_val = strdup( optarg );
483                 {
484                         char* p;
485
486                         for( p = optarg; *p == '\0'; p++ ) {
487                                 *p = '\0';
488                         }
489                 }
490                 passwd.bv_len = strlen( passwd.bv_val );
491             break;
492         case 'W':
493                 want_bindpw++;
494                 break;
495         case 'Y':
496 #ifdef HAVE_CYRUS_SASL
497                 if( sasl_mech != NULL ) {
498                         fprintf( stderr, "%s: -Y previously specified\n" );
499                         return EXIT_FAILURE;
500                 }
501                 if( version == LDAP_VERSION2 ) {
502                         fprintf( stderr, "%s: -Y incompatible with version %d\n",
503                                 prog, version );
504                         return EXIT_FAILURE;
505                 }
506                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
507                         fprintf( stderr, "%s: incompatible with authentication choice\n", prog );
508                         return EXIT_FAILURE;
509                 }
510                 authmethod = LDAP_AUTH_SASL;
511                 version = LDAP_VERSION3;
512                 sasl_mech = strdup( optarg );
513 #else
514                 fprintf( stderr, "%s: not compiled with SASL support\n",
515                         prog );
516                 return( EXIT_FAILURE );
517 #endif
518                 break;
519         case 'x':
520                 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
521                         fprintf( stderr, "%s: incompatible with previous "
522                                 "authentication choice\n", prog );
523                         return EXIT_FAILURE;
524                 }
525                 authmethod = LDAP_AUTH_SIMPLE;
526                 break;
527         case 'X':
528 #ifdef HAVE_CYRUS_SASL
529                 if( sasl_authz_id != NULL ) {
530                         fprintf( stderr, "%s: -X previously specified\n" );
531                         return EXIT_FAILURE;
532                 }
533                 if( version == LDAP_VERSION2 ) {
534                         fprintf( stderr, "%s: -X incompatible with LDAPv%d\n",
535                                 prog, version );
536                         return EXIT_FAILURE;
537                 }
538                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
539                         fprintf( stderr, "%s: -X incompatible with "
540                                 "authentication choice\n", prog );
541                         return EXIT_FAILURE;
542                 }
543                 authmethod = LDAP_AUTH_SASL;
544                 version = LDAP_VERSION3;
545                 sasl_authz_id = strdup( optarg );
546 #else
547                 fprintf( stderr, "%s: not compiled with SASL support\n",
548                         prog );
549                 return( EXIT_FAILURE );
550 #endif
551                 break;
552         case 'Z':
553 #ifdef HAVE_TLS
554                 if( version == LDAP_VERSION2 ) {
555                         fprintf( stderr, "%s: -Z incompatible with version %d\n",
556                                 prog, version );
557                         return EXIT_FAILURE;
558                 }
559                 version = LDAP_VERSION3;
560                 use_tls++;
561 #else
562                 fprintf( stderr, "%s: not compiled with TLS support\n",
563                         prog );
564                 return( EXIT_FAILURE );
565 #endif
566                 break;
567         default:
568                 fprintf( stderr, "%s: unrecongized option -%c\n",
569                         prog, optopt );
570                 usage( argv[0] );
571         }
572         }
573
574         if (version == -1) {
575                 version = LDAP_VERSION3;
576         }
577         if (authmethod == -1 && version > LDAP_VERSION2) {
578 #ifdef HAVE_CYRUS_SASL
579                 authmethod = LDAP_AUTH_SASL;
580 #else
581                 authmethod = LDAP_AUTH_SIMPLE;
582 #endif
583         }
584
585         if (( argc - optind < 1 ) ||
586                 ( strchr( argv[optind], '=' ) == NULL ) )
587         {
588                 filtpattern = "(objectclass=*)";
589         } else {
590                 filtpattern = strdup( argv[optind++] );
591         }
592
593         if ( argv[optind] == NULL ) {
594                 attrs = NULL;
595         } else if ( sortattr == NULL || *sortattr == '\0' ) {
596                 attrs = &argv[optind];
597         }
598
599         if ( infile != NULL ) {
600                 if ( infile[0] == '-' && infile[1] == '\0' ) {
601                         fp = stdin;
602                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
603                         perror( infile );
604                         return EXIT_FAILURE;
605                 }
606         }
607
608         if( tmpdir == NULL
609                 && (tmpdir = getenv("TMPDIR")) == NULL
610                 && (tmpdir = getenv("TMP")) == NULL
611                 && (tmpdir = getenv("TEMP")) == NULL )
612         {
613                 tmpdir = LDAP_TMPDIR;
614         }
615
616         if( urlpre == NULL ) {
617                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
618
619                 if( urlpre == NULL ) {
620                         perror( "malloc" );
621                         return EXIT_FAILURE;
622                 }
623
624                 sprintf( urlpre, "file:///%s/",
625                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
626
627                 /* urlpre should be URLized.... */
628         }
629
630         if ( debug ) {
631                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
632                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
633                 }
634                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
635                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
636                 }
637                 ldif_debug = debug;
638         }
639
640 #ifdef SIGPIPE
641         (void) SIGNAL( SIGPIPE, SIG_IGN );
642 #endif
643
644         if ( verbose ) {
645                 fprintf( stderr,
646                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
647                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
648                         ldapport );
649         }
650
651         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
652                 perror( "ldap_init" );
653                 return EXIT_FAILURE;
654         }
655
656         if (deref != -1 &&
657                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
658         {
659                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
660                 return EXIT_FAILURE;
661         }
662         if (timelimit != -1 &&
663                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
664         {
665                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
666                 return EXIT_FAILURE;
667         }
668         if (sizelimit != -1 &&
669                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
670         {
671                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
672                 return EXIT_FAILURE;
673         }
674
675         /* referrals */
676         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
677                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
678         {
679                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
680                         referrals ? "on" : "off" );
681                 return EXIT_FAILURE;
682         }
683
684         if (version == -1 ) {
685                 version = 3;
686         }
687
688         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
689                 != LDAP_OPT_SUCCESS )
690         {
691                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
692                         version );
693                 return EXIT_FAILURE;
694         }
695
696         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
697                 if ( use_tls > 1 ) {
698                         ldap_perror( ld, "ldap_start_tls" );
699                         return EXIT_FAILURE;
700                 }
701                 fprintf( stderr, "WARNING: could not start TLS\n" );
702         }
703
704         if (want_bindpw) {
705                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
706                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
707         }
708
709         if ( authmethod == LDAP_AUTH_SASL ) {
710 #ifdef HAVE_CYRUS_SASL
711                 void *defaults;
712
713                 if( sasl_secprops != NULL ) {
714                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
715                                 (void *) sasl_secprops );
716                         
717                         if( rc != LDAP_OPT_SUCCESS ) {
718                                 fprintf( stderr,
719                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
720                                         sasl_secprops );
721                                 return( EXIT_FAILURE );
722                         }
723                 }
724                 
725                 defaults = lutil_sasl_defaults( ld,
726                         sasl_mech,
727                         sasl_realm,
728                         sasl_authc_id,
729                         passwd.bv_val,
730                         sasl_authz_id );
731
732                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
733                         sasl_mech, NULL, NULL,
734                         sasl_flags, lutil_sasl_interact, defaults );
735
736                 if( rc != LDAP_SUCCESS ) {
737                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
738                         return( EXIT_FAILURE );
739                 }
740 #else
741                 fprintf( stderr, "%s: not compiled with SASL support\n",
742                         prog, argv[0] );
743                 return( EXIT_FAILURE );
744 #endif
745         } else {
746                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
747                                 != LDAP_SUCCESS ) {
748                         ldap_perror( ld, "ldap_bind" );
749                         return( EXIT_FAILURE );
750                 }
751         }
752
753         if ( manageDSAit ) {
754                 int err;
755                 LDAPControl c;
756                 LDAPControl *ctrls[2];
757                 ctrls[0] = &c;
758                 ctrls[1] = NULL;
759
760                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
761                 c.ldctl_value.bv_val = NULL;
762                 c.ldctl_value.bv_len = 0;
763                 c.ldctl_iscritical = manageDSAit > 1;
764
765                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
766
767                 if( err != LDAP_OPT_SUCCESS ) {
768                         fprintf( stderr, "Could not set ManageDSAit %scontrol\n",
769                                 c.ldctl_iscritical ? "critical " : "" );
770                         if( c.ldctl_iscritical ) {
771                                 exit( EXIT_FAILURE );
772                         }
773                 }
774         }
775
776         if ( verbose ) {
777                 fprintf( stderr, "filter%s: %s\nrequesting: ",
778                         infile != NULL ? " pattern" : "",
779                         filtpattern );
780
781                 if ( attrs == NULL ) {
782                         fprintf( stderr, "ALL" );
783                 } else {
784                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
785                                 fprintf( stderr, "%s ", attrs[ i ] );
786                         }
787                 }
788                 fprintf( stderr, "\n" );
789         }
790
791         if (ldif < 3 ) {
792                 printf( "version: %d\n\n", ldif ? 1 : 2 );
793         }
794
795         if (ldif < 2 ) {
796                 printf( "#\n# filter%s: %s\n# requesting: ",
797                         infile != NULL ? " pattern" : "",
798                         filtpattern );
799
800                 if ( attrs == NULL ) {
801                         printf( "ALL" );
802                 } else {
803                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
804                                 printf( "%s ", attrs[ i ] );
805                         }
806                 }
807
808                 if ( manageDSAit ) {
809                         printf("\n# with manageDSAit %scontrol",
810                                 manageDSAit > 1 ? "critical " : "" );
811                 }
812
813                 printf( "\n#\n\n" );
814         }
815
816         if ( infile == NULL ) {
817                 rc = dosearch( ld, base, scope, NULL, filtpattern,
818                         attrs, attrsonly, NULL, NULL, NULL, -1 );
819
820         } else {
821                 rc = 0;
822                 first = 1;
823                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
824                         line[ strlen( line ) - 1 ] = '\0';
825                         if ( !first ) {
826                                 putchar( '\n' );
827                         } else {
828                                 first = 0;
829                         }
830                         rc = dosearch( ld, base, scope, filtpattern, line,
831                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
832                 }
833                 if ( fp != stdin ) {
834                         fclose( fp );
835                 }
836         }
837
838         ldap_unbind( ld );
839         return( rc );
840 }
841
842
843 static int dosearch(
844         LDAP    *ld,
845         char    *base,
846         int             scope,
847         char    *filtpatt,
848         char    *value,
849         char    **attrs,
850         int             attrsonly,
851         LDAPControl **sctrls,
852         LDAPControl **cctrls,
853         struct timeval *timelimit,
854         int sizelimit )
855 {
856         char            filter[ BUFSIZ ];
857         int                     rc, first;
858         int                     nresponses;
859         int                     nentries;
860         int                     nreferences;
861         int                     nextended;
862         int                     npartial;
863         LDAPMessage             *res, *msg;
864         ber_int_t       msgid;
865
866         if( filtpatt != NULL ) {
867                 sprintf( filter, filtpatt, value );
868
869                 if ( verbose ) {
870                         fprintf( stderr, "filter is: (%s)\n", filter );
871                 }
872
873                 if( ldif < 2 ) {
874                         printf( "#\n# filter: %s\n#\n", filter );
875                 }
876
877         } else {
878                 sprintf( filter, "%s", value );
879         }
880
881         if ( not ) {
882                 return LDAP_SUCCESS;
883         }
884
885         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
886                 sctrls, cctrls, timelimit, sizelimit, &msgid );
887
888         if( rc != LDAP_SUCCESS ) {
889                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
890                         prog, ldap_err2string( rc ), rc );
891                 return( rc );
892         }
893
894         nresponses = nentries = nreferences = nextended = npartial = 0;
895
896         res = NULL;
897
898         while ((rc = ldap_result( ld, LDAP_RES_ANY,
899                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
900                 NULL, &res )) > 0 )
901         {
902                 if( sortattr ) {
903                         (void) ldap_sort_entries( ld, &res,
904                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
905                 }
906
907                 for ( msg = ldap_first_message( ld, res );
908                         msg != NULL;
909                         msg = ldap_next_message( ld, msg ) )
910                 {
911                         if( nresponses++ ) putchar('\n');
912
913                         switch( ldap_msgtype( msg ) ) {
914                         case LDAP_RES_SEARCH_ENTRY:
915                                 nentries++;
916                                 print_entry( ld, msg, attrsonly );
917                                 break;
918
919                         case LDAP_RES_SEARCH_REFERENCE:
920                                 nreferences++;
921                                 print_reference( ld, msg );
922                                 break;
923
924                         case LDAP_RES_EXTENDED:
925                                 nextended++;
926                                 print_extended( ld, msg );
927
928                                 if( ldap_msgid( msg ) == 0 ) {
929                                         /* unsolicited extended operation */
930                                         goto done;
931                                 }
932                                 break;
933
934                         case LDAP_RES_EXTENDED_PARTIAL:
935                                 npartial++;
936                                 print_partial( ld, msg );
937                                 break;
938
939                         case LDAP_RES_SEARCH_RESULT:
940                                 rc = print_result( ld, msg, 1 );
941                                 goto done;
942                         }
943                 }
944
945                 ldap_msgfree( res );
946         }
947
948         if ( rc == -1 ) {
949                 ldap_perror( ld, "ldap_result" );
950                 return( rc );
951         }
952
953 done:
954         if ( ldif < 2 ) {
955                 printf( "\n# numResponses: %d\n", nresponses );
956                 if( nentries ) printf( "# numEntries: %d\n", nentries );
957                 if( nextended ) printf( "# numExtended: %d\n", nextended );
958                 if( npartial ) printf( "# numPartial: %d\n", npartial );
959                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
960         }
961
962         return( rc );
963 }
964
965 static void
966 print_entry(
967         LDAP    *ld,
968         LDAPMessage     *entry,
969         int             attrsonly)
970 {
971         char            *a, *dn, *ufn;
972         char    tmpfname[ 256 ];
973         char    url[ 256 ];
974         int                     i, rc;
975         BerElement              *ber = NULL;
976         struct berval   **bvals;
977         LDAPControl **ctrls = NULL;
978         FILE            *tmpfp;
979
980         dn = ldap_get_dn( ld, entry );
981         ufn = NULL;
982
983         if ( ldif < 2 ) {
984                 ufn = ldap_dn2ufn( dn );
985                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
986         }
987         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
988
989         rc = ldap_get_entry_controls( ld, entry, &ctrls );
990
991         if( rc != LDAP_SUCCESS ) {
992                 fprintf(stderr, "print_entry: %d\n", rc );
993                 ldap_perror( ld, "ldap_get_entry_controls" );
994                 exit( EXIT_FAILURE );
995         }
996
997         if( ctrls ) {
998                 print_ctrls( ctrls );
999                 ldap_controls_free( ctrls );
1000         }
1001
1002         if ( includeufn ) {
1003                 if( ufn == NULL ) {
1004                         ufn = ldap_dn2ufn( dn );
1005                 }
1006                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1007         }
1008
1009         if( ufn != NULL ) ldap_memfree( ufn );
1010         ldap_memfree( dn );
1011
1012         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1013                 a = ldap_next_attribute( ld, entry, ber ) )
1014         {
1015                 if ( attrsonly ) {
1016                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1017
1018                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1019                         for ( i = 0; bvals[i] != NULL; i++ ) {
1020                                 if ( vals2tmp > 1 || ( vals2tmp
1021                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1022                                 {
1023                                         int tmpfd;
1024                                         /* write value to file */
1025                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1026                                                 tmpdir, a );
1027                                         tmpfp = NULL;
1028
1029                                         if ( mktemp( tmpfname ) == NULL ) {
1030                                                 perror( tmpfname );
1031                                                 continue;
1032                                         }
1033
1034                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
1035                                                 perror( tmpfname );
1036                                                 continue;
1037                                         }
1038
1039                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1040                                                 perror( tmpfname );
1041                                                 continue;
1042                                         }
1043
1044                                         if ( fwrite( bvals[ i ]->bv_val,
1045                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1046                                         {
1047                                                 perror( tmpfname );
1048                                                 fclose( tmpfp );
1049                                                 continue;
1050                                         }
1051
1052                                         fclose( tmpfp );
1053
1054                                         sprintf( url, "%s%s", urlpre,
1055                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1056
1057                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1058
1059                                 } else {
1060                                         write_ldif( LDIF_PUT_VALUE, a,
1061                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1062                                 }
1063                         }
1064                         ber_bvecfree( bvals );
1065                 }
1066         }
1067
1068         if( ber != NULL ) {
1069                 ber_free( ber, 0 );
1070         }
1071 }
1072
1073 static void print_reference(
1074         LDAP *ld,
1075         LDAPMessage *reference )
1076 {
1077         int rc;
1078         char **refs = NULL;
1079         LDAPControl **ctrls;
1080
1081         if( ldif < 2 ) {
1082                 printf("# search reference\n");
1083         }
1084
1085         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1086
1087         if( rc != LDAP_SUCCESS ) {
1088                 ldap_perror(ld, "ldap_parse_reference");
1089                 exit( EXIT_FAILURE );
1090         }
1091
1092         if( refs ) {
1093                 int i;
1094                 for( i=0; refs[i] != NULL; i++ ) {
1095                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1096                                 "ref", refs[i], strlen(refs[i]) );
1097                 }
1098                 ber_memvfree( (void **) refs );
1099         }
1100
1101         if( ctrls ) {
1102                 print_ctrls( ctrls );
1103                 ldap_controls_free( ctrls );
1104         }
1105 }
1106
1107 static void print_extended(
1108         LDAP *ld,
1109         LDAPMessage *extended )
1110 {
1111         int rc;
1112         char *retoid = NULL;
1113         struct berval *retdata = NULL;
1114
1115         if( ldif < 2 ) {
1116                 printf("# extended result response\n");
1117         }
1118
1119         rc = ldap_parse_extended_result( ld, extended,
1120                 &retoid, &retdata, 0 );
1121
1122         if( rc != LDAP_SUCCESS ) {
1123                 ldap_perror(ld, "ldap_parse_extended_result");
1124                 exit( EXIT_FAILURE );
1125         }
1126
1127         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1128                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1129         ber_memfree( retoid );
1130
1131         if(retdata) {
1132                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1133                         "data", retdata->bv_val, retdata->bv_len );
1134                 ber_bvfree( retdata );
1135         }
1136
1137         print_result( ld, extended, 0 );
1138 }
1139
1140 static void print_partial(
1141         LDAP *ld,
1142         LDAPMessage *partial )
1143 {
1144         int rc;
1145         char *retoid = NULL;
1146         struct berval *retdata = NULL;
1147         LDAPControl **ctrls = NULL;
1148
1149         if( ldif < 2 ) {
1150                 printf("# extended partial response\n");
1151         }
1152
1153         rc = ldap_parse_extended_partial( ld, partial,
1154                 &retoid, &retdata, &ctrls, 0 );
1155
1156         if( rc != LDAP_SUCCESS ) {
1157                 ldap_perror(ld, "ldap_parse_extended_partial");
1158                 exit( EXIT_FAILURE );
1159         }
1160
1161         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1162                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1163
1164         ber_memfree( retoid );
1165
1166         if( retdata ) {
1167                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1168                         "data", 
1169                         retdata->bv_val, retdata->bv_len );
1170
1171                 ber_bvfree( retdata );
1172         }
1173
1174         if( ctrls ) {
1175                 print_ctrls( ctrls );
1176                 ldap_controls_free( ctrls );
1177         }
1178 }
1179
1180 static int print_result(
1181         LDAP *ld,
1182         LDAPMessage *result, int search )
1183 {
1184         char rst[BUFSIZ];
1185         int rc;
1186         int err;
1187         char *matcheddn = NULL;
1188         char *text = NULL;
1189         char **refs = NULL;
1190         LDAPControl **ctrls = NULL;
1191
1192         if( search ) {
1193                 if ( ldif < 2 ) {
1194                         printf("# search result\n");
1195                 }
1196                 if ( ldif < 1 ) {
1197                         printf("%s: %d\n", "search", ldap_msgid(result) );
1198                 }
1199         }
1200
1201         rc = ldap_parse_result( ld, result,
1202                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1203
1204         if( rc != LDAP_SUCCESS ) {
1205                 ldap_perror(ld, "ldap_parse_result");
1206                 exit( EXIT_FAILURE );
1207         }
1208
1209
1210         if( !ldif ) {
1211                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1212
1213         } else if ( err != LDAP_SUCCESS ) {
1214                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1215         }
1216
1217         if( matcheddn && *matcheddn ) {
1218                 if( !ldif ) {
1219                         write_ldif( LDIF_PUT_VALUE,
1220                                 "matchedDN", matcheddn, strlen(matcheddn) );
1221                 } else {
1222                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1223                 }
1224
1225                 ber_memfree( matcheddn );
1226         }
1227
1228         if( text && *text ) {
1229                 if( !ldif ) {
1230                         write_ldif( LDIF_PUT_TEXT, "text",
1231                                 text, strlen(text) );
1232                 } else {
1233                         fprintf( stderr, "Additional information: %s\n", text );
1234                 }
1235
1236                 ber_memfree( text );
1237         }
1238
1239         if( refs ) {
1240                 int i;
1241                 for( i=0; refs[i] != NULL; i++ ) {
1242                         if( !ldif ) {
1243                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1244                         } else {
1245                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1246                         }
1247                 }
1248
1249                 ber_memvfree( (void **) refs );
1250         }
1251
1252         if( ctrls ) {
1253                 print_ctrls( ctrls );
1254                 ldap_controls_free( ctrls );
1255         }
1256
1257         return err;
1258 }
1259
1260 void print_ctrls( LDAPControl **ctrls ) {
1261         int i;
1262         for(i=0; ctrls[i] != NULL; i++ ) {
1263                 /* control: OID criticality base64value */
1264                 struct berval *b64 = NULL;
1265                 ber_len_t len;
1266                 char *str;
1267                         
1268                 len = strlen( ctrls[i]->ldctl_oid );
1269
1270                 /* add enough for space after OID and the critical value itself */
1271                 len += ctrls[i]->ldctl_iscritical
1272                         ? sizeof("true") : sizeof("false");
1273
1274                 /* convert to base64 */
1275                 if( ctrls[i]->ldctl_value.bv_len ) {
1276                         b64 = ber_memalloc( sizeof(struct berval) );
1277                         
1278                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1279                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1280                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1281
1282                         b64->bv_len = lutil_b64_ntop(
1283                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1284                                 b64->bv_val, b64->bv_len );
1285                 }
1286
1287                 if( b64 ) {
1288                         len += 1 + b64->bv_len;
1289                 }
1290
1291                 str = malloc( len + 1 );
1292                 strcpy( str, ctrls[i]->ldctl_oid );
1293                 strcat( str, ctrls[i]->ldctl_iscritical
1294                         ? " true" : " false" );
1295
1296                 if( b64 ) {
1297                         strcat(str, " ");
1298                         strcat(str, b64->bv_val );
1299                 }
1300
1301                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1302                         "control", str, len );
1303
1304                 free( str );
1305                 ber_bvfree( b64 );
1306         }
1307 }
1308
1309 static int
1310 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1311 {
1312         char    *ldif;
1313
1314         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1315                 return( -1 );
1316         }
1317
1318         fputs( ldif, stdout );
1319         ber_memfree( ldif );
1320
1321         return( 0 );
1322 }