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