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