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