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