]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
01f0510584a35ff1415a75ba9e1833920ef3d916
[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\tdereference aliases: 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 = LUTIL_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 'k':       /* kerberos bind */
274 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
275                 if( version > LDAP_VERSION2 ) {
276                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
277                                 prog, version );
278                         return EXIT_FAILURE;
279                 }
280
281                 if( authmethod != -1 ) {
282                         fprintf( stderr, "%s: -k incompatible with previous "
283                                 "authentication choice\n", prog );
284                         return EXIT_FAILURE;
285                 }
286                         
287                 authmethod = LDAP_AUTH_KRBV4;
288 #else
289                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
290                 return EXIT_FAILURE;
291 #endif
292             break;
293         case 'K':       /* kerberos bind, part one only */
294 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
295                 if( version > LDAP_VERSION2 ) {
296                         fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
297                                 prog, version );
298                         return EXIT_FAILURE;
299                 }
300                 if( authmethod != -1 ) {
301                         fprintf( stderr, "%s: incompatible with previous "
302                                 "authentication choice\n", prog );
303                         return EXIT_FAILURE;
304                 }
305
306                 authmethod = LDAP_AUTH_KRBV41;
307 #else
308                 fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
309                 return( EXIT_FAILURE );
310 #endif
311             break;
312         case 'M':
313                 /* enable Manage DSA IT */
314                 if( version == LDAP_VERSION2 ) {
315                         fprintf( stderr, "%s: -M incompatible with LDAPv%d\n",
316                                 prog, version );
317                         return EXIT_FAILURE;
318                 }
319                 manageDSAit++;
320                 version = LDAP_VERSION3;
321                 break;
322         case 'n':       /* print deletes, don't actually do them */
323             ++not;
324             break;
325         case 'O':
326 #ifdef HAVE_CYRUS_SASL
327                 if( sasl_secprops != NULL ) {
328                         fprintf( stderr, "%s: -O previously specified\n" );
329                         return EXIT_FAILURE;
330                 }
331                 if( version == LDAP_VERSION2 ) {
332                         fprintf( stderr, "%s: -O incompatible with LDAPv%d\n",
333                                 prog, version );
334                         return EXIT_FAILURE;
335                 }
336                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
337                         fprintf( stderr, "%s: incompatible previous "
338                                 "authentication choice\n", prog );
339                         return EXIT_FAILURE;
340                 }
341                 authmethod = LDAP_AUTH_SASL;
342                 version = LDAP_VERSION3;
343                 sasl_secprops = strdup( optarg );
344 #else
345                 fprintf( stderr, "%s: not compiled with SASL support\n",
346                         prog );
347                 return( EXIT_FAILURE );
348 #endif
349                 break;
350         case 'p':
351                 if( ldapport ) {
352                         fprintf( stderr, "%s: -p previously specified\n" );
353                         return EXIT_FAILURE;
354                 }
355             ldapport = atoi( optarg );
356             break;
357         case 'P':
358                 switch( atoi(optarg) ) {
359                 case 2:
360                         if( version == LDAP_VERSION3 ) {
361                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
362                                         prog, version );
363                                 return EXIT_FAILURE;
364                         }
365                         version = LDAP_VERSION2;
366                         break;
367                 case 3:
368                         if( version == LDAP_VERSION2 ) {
369                                 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
370                                         prog, version );
371                                 return EXIT_FAILURE;
372                         }
373                         version = LDAP_VERSION3;
374                         break;
375                 default:
376                         fprintf( stderr, "%s: protocol version should be 2 or 3\n",
377                                 prog );
378                         usage( prog );
379                         return( EXIT_FAILURE );
380                 } break;
381         case 'Q':
382 #ifdef HAVE_CYRUS_SASL
383                 if( version == LDAP_VERSION2 ) {
384                         fprintf( stderr, "%s: -Q incompatible with version %d\n",
385                                 prog, version );
386                         return EXIT_FAILURE;
387                 }
388                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
389                         fprintf( stderr, "%s: incompatible previous "
390                                 "authentication choice\n",
391                                 prog );
392                         return EXIT_FAILURE;
393                 }
394                 authmethod = LDAP_AUTH_SASL;
395                 version = LDAP_VERSION3;
396                 sasl_flags = LUTIL_SASL_QUIET;
397 #else
398                 fprintf( stderr, "%s: was not compiled with SASL support\n",
399                         prog );
400                 return( EXIT_FAILURE );
401 #endif
402         case 'R':
403 #ifdef HAVE_CYRUS_SASL
404                 if( sasl_realm != NULL ) {
405                         fprintf( stderr, "%s: -R previously specified\n" );
406                         return EXIT_FAILURE;
407                 }
408                 if( version == LDAP_VERSION2 ) {
409                         fprintf( stderr, "%s: -R incompatible with version %d\n",
410                                 prog, version );
411                         return EXIT_FAILURE;
412                 }
413                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
414                         fprintf( stderr, "%s: incompatible previous "
415                                 "authentication choice\n",
416                                 prog );
417                         return EXIT_FAILURE;
418                 }
419                 authmethod = LDAP_AUTH_SASL;
420                 version = LDAP_VERSION3;
421                 sasl_realm = strdup( optarg );
422 #else
423                 fprintf( stderr, "%s: was not compiled with SASL support\n",
424                         prog );
425                 return( EXIT_FAILURE );
426 #endif
427                 break;
428         case 'U':
429 #ifdef HAVE_CYRUS_SASL
430                 if( sasl_authc_id != NULL ) {
431                         fprintf( stderr, "%s: -U previously specified\n" );
432                         return EXIT_FAILURE;
433                 }
434                 if( version == LDAP_VERSION2 ) {
435                         fprintf( stderr, "%s: -U incompatible with version %d\n",
436                                 prog, version );
437                         return EXIT_FAILURE;
438                 }
439                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
440                         fprintf( stderr, "%s: incompatible previous "
441                                 "authentication choice\n",
442                                 prog );
443                         return EXIT_FAILURE;
444                 }
445                 authmethod = LDAP_AUTH_SASL;
446                 version = LDAP_VERSION3;
447                 sasl_authc_id = strdup( optarg );
448 #else
449                 fprintf( stderr, "%s: was not compiled with SASL support\n",
450                         prog );
451                 return( EXIT_FAILURE );
452 #endif
453                 break;
454         case 'v':       /* verbose mode */
455             verbose++;
456             break;
457         case 'w':       /* password */
458             passwd.bv_val = strdup( optarg );
459                 {
460                         char* p;
461
462                         for( p = optarg; *p == '\0'; p++ ) {
463                                 *p = '\0';
464                         }
465                 }
466                 passwd.bv_len = strlen( passwd.bv_val );
467             break;
468         case 'W':
469                 want_bindpw++;
470                 break;
471         case 'Y':
472 #ifdef HAVE_CYRUS_SASL
473                 if( sasl_mech != NULL ) {
474                         fprintf( stderr, "%s: -Y previously specified\n" );
475                         return EXIT_FAILURE;
476                 }
477                 if( version == LDAP_VERSION2 ) {
478                         fprintf( stderr, "%s: -Y incompatible with version %d\n",
479                                 prog, version );
480                         return EXIT_FAILURE;
481                 }
482                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
483                         fprintf( stderr, "%s: incompatible with authentication choice\n", prog );
484                         return EXIT_FAILURE;
485                 }
486                 authmethod = LDAP_AUTH_SASL;
487                 version = LDAP_VERSION3;
488                 sasl_mech = strdup( optarg );
489 #else
490                 fprintf( stderr, "%s: was not compiled with SASL support\n",
491                         prog );
492                 return( EXIT_FAILURE );
493 #endif
494                 break;
495         case 'x':
496                 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
497                         fprintf( stderr, "%s: incompatible with previous "
498                                 "authentication choice\n", prog );
499                         return EXIT_FAILURE;
500                 }
501                 authmethod = LDAP_AUTH_SIMPLE;
502                 break;
503         case 'X':
504 #ifdef HAVE_CYRUS_SASL
505                 if( sasl_authz_id != NULL ) {
506                         fprintf( stderr, "%s: -X previously specified\n" );
507                         return EXIT_FAILURE;
508                 }
509                 if( version == LDAP_VERSION2 ) {
510                         fprintf( stderr, "%s: -X incompatible with LDAPv%d\n",
511                                 prog, version );
512                         return EXIT_FAILURE;
513                 }
514                 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
515                         fprintf( stderr, "%s: -X incompatible with "
516                                 "authentication choice\n", prog );
517                         return EXIT_FAILURE;
518                 }
519                 authmethod = LDAP_AUTH_SASL;
520                 version = LDAP_VERSION3;
521                 sasl_authz_id = strdup( optarg );
522 #else
523                 fprintf( stderr, "%s: not compiled with SASL support\n",
524                         prog );
525                 return( EXIT_FAILURE );
526 #endif
527                 break;
528         case 'Z':
529 #ifdef HAVE_TLS
530                 if( version == LDAP_VERSION2 ) {
531                         fprintf( stderr, "%s -Z incompatible with version %d\n",
532                                 prog, version );
533                         return EXIT_FAILURE;
534                 }
535                 version = LDAP_VERSION3;
536                 use_tls++;
537 #else
538                 fprintf( stderr, "%s: not compiled with TLS support\n",
539                         prog );
540                 return( EXIT_FAILURE );
541 #endif
542                 break;
543         default:
544                 fprintf( stderr, "%s: unrecongized option -%c\n",
545                         prog, optopt );
546                 usage( argv[0] );
547         }
548         }
549
550         if (version == -1) {
551                 version = LDAP_VERSION3;
552         }
553         if (authmethod == -1 && version > LDAP_VERSION2) {
554 #ifdef HAVE_CYRUS_SASL
555                 authmethod = LDAP_AUTH_SASL;
556 #else
557                 authmethod = LDAP_AUTH_SIMPLE;
558 #endif
559         }
560
561         if (( argc - optind < 1 ) ||
562                 ( strchr( argv[optind], '=' ) == NULL ) )
563         {
564                 filtpattern = "(objectclass=*)";
565         } else {
566                 filtpattern = strdup( argv[optind++] );
567         }
568
569         if ( argv[optind] == NULL ) {
570                 attrs = NULL;
571         } else if ( sortattr == NULL || *sortattr == '\0' ) {
572                 attrs = &argv[optind];
573         }
574
575         if ( infile != NULL ) {
576                 if ( infile[0] == '-' && infile[1] == '\0' ) {
577                         fp = stdin;
578                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
579                         perror( infile );
580                         return EXIT_FAILURE;
581                 }
582         }
583
584         if( tmpdir == NULL
585                 && (tmpdir = getenv("TMPDIR")) == NULL
586                 && (tmpdir = getenv("TMP")) == NULL
587                 && (tmpdir = getenv("TEMP")) == NULL )
588         {
589                 tmpdir = LDAP_TMPDIR;
590         }
591
592         if( urlpre == NULL ) {
593                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
594
595                 if( urlpre == NULL ) {
596                         perror( "malloc" );
597                         return EXIT_FAILURE;
598                 }
599
600                 sprintf( urlpre, "file:///%s/",
601                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
602
603                 /* urlpre should be URLized.... */
604         }
605
606         if ( debug ) {
607                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
608                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
609                 }
610                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
611                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
612                 }
613                 ldif_debug = debug;
614         }
615
616 #ifdef SIGPIPE
617         (void) SIGNAL( SIGPIPE, SIG_IGN );
618 #endif
619
620         if ( verbose ) {
621                 fprintf( stderr,
622                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
623                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
624                         ldapport );
625         }
626
627         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
628                 perror( "ldap_init" );
629                 return EXIT_FAILURE;
630         }
631
632         if (deref != -1 &&
633                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
634         {
635                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
636                 return EXIT_FAILURE;
637         }
638         if (timelimit != -1 &&
639                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
640         {
641                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
642                 return EXIT_FAILURE;
643         }
644         if (sizelimit != -1 &&
645                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
646         {
647                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
648                 return EXIT_FAILURE;
649         }
650
651         /* referrals */
652         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
653                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
654         {
655                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
656                         referrals ? "on" : "off" );
657                 return EXIT_FAILURE;
658         }
659
660         if (version == -1 ) {
661                 version = 3;
662         }
663
664         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
665                 != LDAP_OPT_SUCCESS )
666         {
667                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
668                         version );
669                 return EXIT_FAILURE;
670         }
671
672         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
673                 if ( use_tls > 1 ) {
674                         ldap_perror( ld, "ldap_start_tls" );
675                         return EXIT_FAILURE;
676                 }
677                 fprintf( stderr, "WARNING: could not start TLS\n" );
678         }
679
680         if (want_bindpw) {
681                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
682                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
683         }
684
685         if ( authmethod == LDAP_AUTH_SASL ) {
686 #ifdef HAVE_CYRUS_SASL
687                 void *defaults;
688
689                 if( sasl_secprops != NULL ) {
690                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
691                                 (void *) sasl_secprops );
692                         
693                         if( rc != LDAP_OPT_SUCCESS ) {
694                                 fprintf( stderr,
695                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
696                                         sasl_secprops );
697                                 return( EXIT_FAILURE );
698                         }
699                 }
700                 
701                 defaults = lutil_sasl_defaults( ld, sasl_flags,
702                         sasl_mech,
703                         sasl_realm,
704                         sasl_authc_id,
705                         passwd.bv_val,
706                         sasl_authz_id );
707
708                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
709                         sasl_mech, NULL, NULL,
710                         lutil_sasl_interact, defaults );
711
712                 if( rc != LDAP_SUCCESS ) {
713                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
714                         return( EXIT_FAILURE );
715                 }
716 #else
717                 fprintf( stderr, "%s was not compiled with SASL support\n",
718                         argv[0] );
719                 return( EXIT_FAILURE );
720 #endif
721         } else {
722                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
723                                 != LDAP_SUCCESS ) {
724                         ldap_perror( ld, "ldap_bind" );
725                         return( EXIT_FAILURE );
726                 }
727         }
728
729         if ( manageDSAit ) {
730                 int err;
731                 LDAPControl c;
732                 LDAPControl *ctrls[2];
733                 ctrls[0] = &c;
734                 ctrls[1] = NULL;
735
736                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
737                 c.ldctl_value.bv_val = NULL;
738                 c.ldctl_value.bv_len = 0;
739                 c.ldctl_iscritical = manageDSAit > 1;
740
741                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
742
743                 if( err != LDAP_OPT_SUCCESS ) {
744                         fprintf( stderr, "Could not set ManageDSAit %scontrol\n",
745                                 c.ldctl_iscritical ? "critical " : "" );
746                         if( c.ldctl_iscritical ) {
747                                 exit( EXIT_FAILURE );
748                         }
749                 }
750         }
751
752         if ( verbose ) {
753                 fprintf( stderr, "filter%s: %s\nrequesting: ",
754                         infile != NULL ? " pattern" : "",
755                         filtpattern );
756
757                 if ( attrs == NULL ) {
758                         fprintf( stderr, "ALL" );
759                 } else {
760                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
761                                 fprintf( stderr, "%s ", attrs[ i ] );
762                         }
763                 }
764                 fprintf( stderr, "\n" );
765         }
766
767         if (ldif < 3 ) {
768                 printf( "version: %d\n\n", ldif ? 1 : 2 );
769         }
770
771         if (ldif < 2 ) {
772                 printf( "#\n# filter%s: %s\n# requesting: ",
773                         infile != NULL ? " pattern" : "",
774                         filtpattern );
775
776                 if ( attrs == NULL ) {
777                         printf( "ALL" );
778                 } else {
779                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
780                                 printf( "%s ", attrs[ i ] );
781                         }
782                 }
783
784                 if ( manageDSAit ) {
785                         printf("\n# with manageDSAit %scontrol",
786                                 manageDSAit > 1 ? "critical " : "" );
787                 }
788
789                 printf( "\n#\n\n" );
790         }
791
792         if ( infile == NULL ) {
793                 rc = dosearch( ld, base, scope, NULL, filtpattern,
794                         attrs, attrsonly, NULL, NULL, NULL, -1 );
795
796         } else {
797                 rc = 0;
798                 first = 1;
799                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
800                         line[ strlen( line ) - 1 ] = '\0';
801                         if ( !first ) {
802                                 putchar( '\n' );
803                         } else {
804                                 first = 0;
805                         }
806                         rc = dosearch( ld, base, scope, filtpattern, line,
807                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
808                 }
809                 if ( fp != stdin ) {
810                         fclose( fp );
811                 }
812         }
813
814         ldap_unbind( ld );
815         return( rc );
816 }
817
818
819 static int dosearch(
820         LDAP    *ld,
821         char    *base,
822         int             scope,
823         char    *filtpatt,
824         char    *value,
825         char    **attrs,
826         int             attrsonly,
827         LDAPControl **sctrls,
828         LDAPControl **cctrls,
829         struct timeval *timelimit,
830         int sizelimit )
831 {
832         char            filter[ BUFSIZ ];
833         int                     rc, first;
834         int                     nresponses;
835         int                     nentries;
836         int                     nreferences;
837         int                     nextended;
838         int                     npartial;
839         LDAPMessage             *res, *msg;
840         ber_int_t       msgid;
841
842         if( filtpatt != NULL ) {
843                 sprintf( filter, filtpatt, value );
844
845                 if ( verbose ) {
846                         fprintf( stderr, "filter is: (%s)\n", filter );
847                 }
848
849                 if( ldif < 2 ) {
850                         printf( "#\n# filter: %s\n#\n", filter );
851                 }
852
853         } else {
854                 sprintf( filter, "%s", value );
855         }
856
857         if ( not ) {
858                 return LDAP_SUCCESS;
859         }
860
861         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
862                 sctrls, cctrls, timelimit, sizelimit, &msgid );
863
864         if( rc != LDAP_SUCCESS ) {
865                 fprintf( stderr, "ldapsearch: ldap_search_ext: %s (%d)\n",
866                         ldap_err2string( rc ), rc );
867                 return( rc );
868         }
869
870         nresponses = nentries = nreferences = nextended = npartial = 0;
871
872         res = NULL;
873
874         while ((rc = ldap_result( ld, LDAP_RES_ANY,
875                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
876                 NULL, &res )) > 0 )
877         {
878                 if( sortattr ) {
879                         (void) ldap_sort_entries( ld, &res,
880                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
881                 }
882
883                 for ( msg = ldap_first_message( ld, res );
884                         msg != NULL;
885                         msg = ldap_next_message( ld, msg ) )
886                 {
887                         if( nresponses++ ) putchar('\n');
888
889                         switch( ldap_msgtype( msg ) ) {
890                         case LDAP_RES_SEARCH_ENTRY:
891                                 nentries++;
892                                 print_entry( ld, msg, attrsonly );
893                                 break;
894
895                         case LDAP_RES_SEARCH_REFERENCE:
896                                 nreferences++;
897                                 print_reference( ld, msg );
898                                 break;
899
900                         case LDAP_RES_EXTENDED:
901                                 nextended++;
902                                 print_extended( ld, msg );
903
904                                 if( ldap_msgid( msg ) == 0 ) {
905                                         /* unsolicited extended operation */
906                                         goto done;
907                                 }
908                                 break;
909
910                         case LDAP_RES_EXTENDED_PARTIAL:
911                                 npartial++;
912                                 print_partial( ld, msg );
913                                 break;
914
915                         case LDAP_RES_SEARCH_RESULT:
916                                 rc = print_result( ld, msg, 1 );
917                                 goto done;
918                         }
919                 }
920
921                 ldap_msgfree( res );
922         }
923
924         if ( rc == -1 ) {
925                 ldap_perror( ld, "ldap_result" );
926                 return( rc );
927         }
928
929 done:
930         if ( ldif < 2 ) {
931                 printf( "\n# numResponses: %d\n", nresponses );
932                 if( nentries ) printf( "# numEntries: %d\n", nentries );
933                 if( nextended ) printf( "# numExtended: %d\n", nextended );
934                 if( npartial ) printf( "# numPartial: %d\n", npartial );
935                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
936         }
937
938         return( rc );
939 }
940
941 static void
942 print_entry(
943         LDAP    *ld,
944         LDAPMessage     *entry,
945         int             attrsonly)
946 {
947         char            *a, *dn, *ufn;
948         char    tmpfname[ 256 ];
949         char    url[ 256 ];
950         int                     i, rc;
951         BerElement              *ber = NULL;
952         struct berval   **bvals;
953         LDAPControl **ctrls = NULL;
954         FILE            *tmpfp;
955
956         dn = ldap_get_dn( ld, entry );
957         ufn = NULL;
958
959         if ( ldif < 2 ) {
960                 ufn = ldap_dn2ufn( dn );
961                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
962         }
963         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
964
965         rc = ldap_get_entry_controls( ld, entry, &ctrls );
966
967         if( rc != LDAP_SUCCESS ) {
968                 fprintf(stderr, "print_entry: %d\n", rc );
969                 ldap_perror( ld, "ldap_get_entry_controls" );
970                 exit( EXIT_FAILURE );
971         }
972
973         if( ctrls ) {
974                 print_ctrls( ctrls );
975                 ldap_controls_free( ctrls );
976         }
977
978         if ( includeufn ) {
979                 if( ufn == NULL ) {
980                         ufn = ldap_dn2ufn( dn );
981                 }
982                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
983         }
984
985         if( ufn != NULL ) ldap_memfree( ufn );
986         ldap_memfree( dn );
987
988         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
989                 a = ldap_next_attribute( ld, entry, ber ) )
990         {
991                 if ( attrsonly ) {
992                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
993
994                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
995                         for ( i = 0; bvals[i] != NULL; i++ ) {
996                                 if ( vals2tmp > 1 || ( vals2tmp
997                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
998                                 {
999                                         int tmpfd;
1000                                         /* write value to file */
1001                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1002                                                 tmpdir, a );
1003                                         tmpfp = NULL;
1004
1005                                         if ( mktemp( tmpfname ) == NULL ) {
1006                                                 perror( tmpfname );
1007                                                 continue;
1008                                         }
1009
1010                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
1011                                                 perror( tmpfname );
1012                                                 continue;
1013                                         }
1014
1015                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1016                                                 perror( tmpfname );
1017                                                 continue;
1018                                         }
1019
1020                                         if ( fwrite( bvals[ i ]->bv_val,
1021                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1022                                         {
1023                                                 perror( tmpfname );
1024                                                 fclose( tmpfp );
1025                                                 continue;
1026                                         }
1027
1028                                         fclose( tmpfp );
1029
1030                                         sprintf( url, "%s%s", urlpre,
1031                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1032
1033                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1034
1035                                 } else {
1036                                         write_ldif( LDIF_PUT_VALUE, a,
1037                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1038                                 }
1039                         }
1040                         ber_bvecfree( bvals );
1041                 }
1042         }
1043
1044         if( ber != NULL ) {
1045                 ber_free( ber, 0 );
1046         }
1047 }
1048
1049 static void print_reference(
1050         LDAP *ld,
1051         LDAPMessage *reference )
1052 {
1053         int rc;
1054         char **refs = NULL;
1055         LDAPControl **ctrls;
1056
1057         if( ldif < 2 ) {
1058                 printf("# search reference\n");
1059         }
1060
1061         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1062
1063         if( rc != LDAP_SUCCESS ) {
1064                 ldap_perror(ld, "ldap_parse_reference");
1065                 exit( EXIT_FAILURE );
1066         }
1067
1068         if( refs ) {
1069                 int i;
1070                 for( i=0; refs[i] != NULL; i++ ) {
1071                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1072                                 "ref", refs[i], strlen(refs[i]) );
1073                 }
1074                 ber_memvfree( (void **) refs );
1075         }
1076
1077         if( ctrls ) {
1078                 print_ctrls( ctrls );
1079                 ldap_controls_free( ctrls );
1080         }
1081 }
1082
1083 static void print_extended(
1084         LDAP *ld,
1085         LDAPMessage *extended )
1086 {
1087         int rc;
1088         char *retoid = NULL;
1089         struct berval *retdata = NULL;
1090
1091         if( ldif < 2 ) {
1092                 printf("# extended result response\n");
1093         }
1094
1095         rc = ldap_parse_extended_result( ld, extended,
1096                 &retoid, &retdata, 0 );
1097
1098         if( rc != LDAP_SUCCESS ) {
1099                 ldap_perror(ld, "ldap_parse_extended_result");
1100                 exit( EXIT_FAILURE );
1101         }
1102
1103         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1104                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1105         ber_memfree( retoid );
1106
1107         if(retdata) {
1108                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1109                         "data", retdata->bv_val, retdata->bv_len );
1110                 ber_bvfree( retdata );
1111         }
1112
1113         print_result( ld, extended, 0 );
1114 }
1115
1116 static void print_partial(
1117         LDAP *ld,
1118         LDAPMessage *partial )
1119 {
1120         int rc;
1121         char *retoid = NULL;
1122         struct berval *retdata = NULL;
1123         LDAPControl **ctrls = NULL;
1124
1125         if( ldif < 2 ) {
1126                 printf("# extended partial response\n");
1127         }
1128
1129         rc = ldap_parse_extended_partial( ld, partial,
1130                 &retoid, &retdata, &ctrls, 0 );
1131
1132         if( rc != LDAP_SUCCESS ) {
1133                 ldap_perror(ld, "ldap_parse_extended_partial");
1134                 exit( EXIT_FAILURE );
1135         }
1136
1137         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1138                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1139
1140         ber_memfree( retoid );
1141
1142         if( retdata ) {
1143                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1144                         "data", 
1145                         retdata->bv_val, retdata->bv_len );
1146
1147                 ber_bvfree( retdata );
1148         }
1149
1150         if( ctrls ) {
1151                 print_ctrls( ctrls );
1152                 ldap_controls_free( ctrls );
1153         }
1154 }
1155
1156 static int print_result(
1157         LDAP *ld,
1158         LDAPMessage *result, int search )
1159 {
1160         char rst[BUFSIZ];
1161         int rc;
1162         int err;
1163         char *matcheddn = NULL;
1164         char *text = NULL;
1165         char **refs = NULL;
1166         LDAPControl **ctrls = NULL;
1167
1168         if( search ) {
1169                 if ( ldif < 2 ) {
1170                         printf("# search result\n");
1171                 }
1172                 if ( ldif < 1 ) {
1173                         printf("%s: %d\n", "search", ldap_msgid(result) );
1174                 }
1175         }
1176
1177         rc = ldap_parse_result( ld, result,
1178                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1179
1180         if( rc != LDAP_SUCCESS ) {
1181                 ldap_perror(ld, "ldap_parse_result");
1182                 exit( EXIT_FAILURE );
1183         }
1184
1185
1186         if( !ldif ) {
1187                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1188
1189         } else if ( err != LDAP_SUCCESS ) {
1190                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1191         }
1192
1193         if( matcheddn && *matcheddn ) {
1194                 if( !ldif ) {
1195                         write_ldif( LDIF_PUT_VALUE,
1196                                 "matchedDN", matcheddn, strlen(matcheddn) );
1197                 } else {
1198                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1199                 }
1200
1201                 ber_memfree( matcheddn );
1202         }
1203
1204         if( text && *text ) {
1205                 if( !ldif ) {
1206                         write_ldif( LDIF_PUT_TEXT, "text",
1207                                 text, strlen(text) );
1208                 } else {
1209                         fprintf( stderr, "Additional information: %s\n", text );
1210                 }
1211
1212                 ber_memfree( text );
1213         }
1214
1215         if( refs ) {
1216                 int i;
1217                 for( i=0; refs[i] != NULL; i++ ) {
1218                         if( !ldif ) {
1219                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1220                         } else {
1221                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1222                         }
1223                 }
1224
1225                 ber_memvfree( (void **) refs );
1226         }
1227
1228         if( ctrls ) {
1229                 print_ctrls( ctrls );
1230                 ldap_controls_free( ctrls );
1231         }
1232
1233         return err;
1234 }
1235
1236 void print_ctrls( LDAPControl **ctrls ) {
1237         int i;
1238         for(i=0; ctrls[i] != NULL; i++ ) {
1239                 /* control: OID criticality base64value */
1240                 struct berval *b64 = NULL;
1241                 ber_len_t len;
1242                 char *str;
1243                         
1244                 len = strlen( ctrls[i]->ldctl_oid );
1245
1246                 /* add enough for space after OID and the critical value itself */
1247                 len += ctrls[i]->ldctl_iscritical
1248                         ? sizeof("true") : sizeof("false");
1249
1250                 /* convert to base64 */
1251                 if( ctrls[i]->ldctl_value.bv_len ) {
1252                         b64 = ber_memalloc( sizeof(struct berval) );
1253                         
1254                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1255                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1256                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1257
1258                         b64->bv_len = lutil_b64_ntop(
1259                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1260                                 b64->bv_val, b64->bv_len );
1261                 }
1262
1263                 if( b64 ) {
1264                         len += 1 + b64->bv_len;
1265                 }
1266
1267                 str = malloc( len + 1 );
1268                 strcpy( str, ctrls[i]->ldctl_oid );
1269                 strcat( str, ctrls[i]->ldctl_iscritical
1270                         ? " true" : " false" );
1271
1272                 if( b64 ) {
1273                         strcat(str, " ");
1274                         strcat(str, b64->bv_val );
1275                 }
1276
1277                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1278                         "control", str, len );
1279
1280                 free( str );
1281                 ber_bvfree( b64 );
1282         }
1283 }
1284
1285 static int
1286 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1287 {
1288         char    *ldif;
1289
1290         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1291                 return( -1 );
1292         }
1293
1294         fputs( ldif, stdout );
1295         ber_memfree( ldif );
1296
1297         return( 0 );
1298 }