]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Add support of "-H uri"
[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", rc );
684                 return EXIT_FAILURE;
685         }
686
687         if (deref != -1 &&
688                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
689         {
690                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
691                 return EXIT_FAILURE;
692         }
693         if (timelimit != -1 &&
694                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
695         {
696                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
697                 return EXIT_FAILURE;
698         }
699         if (sizelimit != -1 &&
700                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
701         {
702                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
703                 return EXIT_FAILURE;
704         }
705
706         /* referrals */
707         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
708                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
709         {
710                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
711                         referrals ? "on" : "off" );
712                 return EXIT_FAILURE;
713         }
714
715         if (version == -1 ) {
716                 version = 3;
717         }
718
719         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
720                 != LDAP_OPT_SUCCESS )
721         {
722                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
723                         version );
724                 return EXIT_FAILURE;
725         }
726
727         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
728                 if ( use_tls > 1 ) {
729                         ldap_perror( ld, "ldap_start_tls" );
730                         return EXIT_FAILURE;
731                 }
732                 fprintf( stderr, "WARNING: could not start TLS\n" );
733         }
734
735         if (want_bindpw) {
736                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
737                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
738         }
739
740         if ( authmethod == LDAP_AUTH_SASL ) {
741 #ifdef HAVE_CYRUS_SASL
742                 void *defaults;
743
744                 if( sasl_secprops != NULL ) {
745                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
746                                 (void *) sasl_secprops );
747                         
748                         if( rc != LDAP_OPT_SUCCESS ) {
749                                 fprintf( stderr,
750                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
751                                         sasl_secprops );
752                                 return( EXIT_FAILURE );
753                         }
754                 }
755                 
756                 defaults = lutil_sasl_defaults( ld,
757                         sasl_mech,
758                         sasl_realm,
759                         sasl_authc_id,
760                         passwd.bv_val,
761                         sasl_authz_id );
762
763                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
764                         sasl_mech, NULL, NULL,
765                         sasl_flags, lutil_sasl_interact, defaults );
766
767                 if( rc != LDAP_SUCCESS ) {
768                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
769                         return( EXIT_FAILURE );
770                 }
771 #else
772                 fprintf( stderr, "%s: not compiled with SASL support\n",
773                         prog, argv[0] );
774                 return( EXIT_FAILURE );
775 #endif
776         } else {
777                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
778                                 != LDAP_SUCCESS ) {
779                         ldap_perror( ld, "ldap_bind" );
780                         return( EXIT_FAILURE );
781                 }
782         }
783
784         if ( manageDSAit ) {
785                 int err;
786                 LDAPControl c;
787                 LDAPControl *ctrls[2];
788                 ctrls[0] = &c;
789                 ctrls[1] = NULL;
790
791                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
792                 c.ldctl_value.bv_val = NULL;
793                 c.ldctl_value.bv_len = 0;
794                 c.ldctl_iscritical = manageDSAit > 1;
795
796                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
797
798                 if( err != LDAP_OPT_SUCCESS ) {
799                         fprintf( stderr, "Could not set ManageDSAit %scontrol\n",
800                                 c.ldctl_iscritical ? "critical " : "" );
801                         if( c.ldctl_iscritical ) {
802                                 exit( EXIT_FAILURE );
803                         }
804                 }
805         }
806
807         if ( verbose ) {
808                 fprintf( stderr, "filter%s: %s\nrequesting: ",
809                         infile != NULL ? " pattern" : "",
810                         filtpattern );
811
812                 if ( attrs == NULL ) {
813                         fprintf( stderr, "ALL" );
814                 } else {
815                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
816                                 fprintf( stderr, "%s ", attrs[ i ] );
817                         }
818                 }
819                 fprintf( stderr, "\n" );
820         }
821
822         if (ldif < 3 ) {
823                 printf( "version: %d\n\n", ldif ? 1 : 2 );
824         }
825
826         if (ldif < 2 ) {
827                 printf( "#\n# filter%s: %s\n# requesting: ",
828                         infile != NULL ? " pattern" : "",
829                         filtpattern );
830
831                 if ( attrs == NULL ) {
832                         printf( "ALL" );
833                 } else {
834                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
835                                 printf( "%s ", attrs[ i ] );
836                         }
837                 }
838
839                 if ( manageDSAit ) {
840                         printf("\n# with manageDSAit %scontrol",
841                                 manageDSAit > 1 ? "critical " : "" );
842                 }
843
844                 printf( "\n#\n\n" );
845         }
846
847         if ( infile == NULL ) {
848                 rc = dosearch( ld, base, scope, NULL, filtpattern,
849                         attrs, attrsonly, NULL, NULL, NULL, -1 );
850
851         } else {
852                 rc = 0;
853                 first = 1;
854                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
855                         line[ strlen( line ) - 1 ] = '\0';
856                         if ( !first ) {
857                                 putchar( '\n' );
858                         } else {
859                                 first = 0;
860                         }
861                         rc = dosearch( ld, base, scope, filtpattern, line,
862                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
863                 }
864                 if ( fp != stdin ) {
865                         fclose( fp );
866                 }
867         }
868
869         ldap_unbind( ld );
870         return( rc );
871 }
872
873
874 static int dosearch(
875         LDAP    *ld,
876         char    *base,
877         int             scope,
878         char    *filtpatt,
879         char    *value,
880         char    **attrs,
881         int             attrsonly,
882         LDAPControl **sctrls,
883         LDAPControl **cctrls,
884         struct timeval *timelimit,
885         int sizelimit )
886 {
887         char            filter[ BUFSIZ ];
888         int                     rc, first;
889         int                     nresponses;
890         int                     nentries;
891         int                     nreferences;
892         int                     nextended;
893         int                     npartial;
894         LDAPMessage             *res, *msg;
895         ber_int_t       msgid;
896
897         if( filtpatt != NULL ) {
898                 sprintf( filter, filtpatt, value );
899
900                 if ( verbose ) {
901                         fprintf( stderr, "filter is: (%s)\n", filter );
902                 }
903
904                 if( ldif < 2 ) {
905                         printf( "#\n# filter: %s\n#\n", filter );
906                 }
907
908         } else {
909                 sprintf( filter, "%s", value );
910         }
911
912         if ( not ) {
913                 return LDAP_SUCCESS;
914         }
915
916         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
917                 sctrls, cctrls, timelimit, sizelimit, &msgid );
918
919         if( rc != LDAP_SUCCESS ) {
920                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
921                         prog, ldap_err2string( rc ), rc );
922                 return( rc );
923         }
924
925         nresponses = nentries = nreferences = nextended = npartial = 0;
926
927         res = NULL;
928
929         while ((rc = ldap_result( ld, LDAP_RES_ANY,
930                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
931                 NULL, &res )) > 0 )
932         {
933                 if( sortattr ) {
934                         (void) ldap_sort_entries( ld, &res,
935                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
936                 }
937
938                 for ( msg = ldap_first_message( ld, res );
939                         msg != NULL;
940                         msg = ldap_next_message( ld, msg ) )
941                 {
942                         if( nresponses++ ) putchar('\n');
943
944                         switch( ldap_msgtype( msg ) ) {
945                         case LDAP_RES_SEARCH_ENTRY:
946                                 nentries++;
947                                 print_entry( ld, msg, attrsonly );
948                                 break;
949
950                         case LDAP_RES_SEARCH_REFERENCE:
951                                 nreferences++;
952                                 print_reference( ld, msg );
953                                 break;
954
955                         case LDAP_RES_EXTENDED:
956                                 nextended++;
957                                 print_extended( ld, msg );
958
959                                 if( ldap_msgid( msg ) == 0 ) {
960                                         /* unsolicited extended operation */
961                                         goto done;
962                                 }
963                                 break;
964
965                         case LDAP_RES_EXTENDED_PARTIAL:
966                                 npartial++;
967                                 print_partial( ld, msg );
968                                 break;
969
970                         case LDAP_RES_SEARCH_RESULT:
971                                 rc = print_result( ld, msg, 1 );
972                                 goto done;
973                         }
974                 }
975
976                 ldap_msgfree( res );
977         }
978
979         if ( rc == -1 ) {
980                 ldap_perror( ld, "ldap_result" );
981                 return( rc );
982         }
983
984 done:
985         if ( ldif < 2 ) {
986                 printf( "\n# numResponses: %d\n", nresponses );
987                 if( nentries ) printf( "# numEntries: %d\n", nentries );
988                 if( nextended ) printf( "# numExtended: %d\n", nextended );
989                 if( npartial ) printf( "# numPartial: %d\n", npartial );
990                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
991         }
992
993         return( rc );
994 }
995
996 static void
997 print_entry(
998         LDAP    *ld,
999         LDAPMessage     *entry,
1000         int             attrsonly)
1001 {
1002         char            *a, *dn, *ufn;
1003         char    tmpfname[ 256 ];
1004         char    url[ 256 ];
1005         int                     i, rc;
1006         BerElement              *ber = NULL;
1007         struct berval   **bvals;
1008         LDAPControl **ctrls = NULL;
1009         FILE            *tmpfp;
1010
1011         dn = ldap_get_dn( ld, entry );
1012         ufn = NULL;
1013
1014         if ( ldif < 2 ) {
1015                 ufn = ldap_dn2ufn( dn );
1016                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1017         }
1018         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
1019
1020         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1021
1022         if( rc != LDAP_SUCCESS ) {
1023                 fprintf(stderr, "print_entry: %d\n", rc );
1024                 ldap_perror( ld, "ldap_get_entry_controls" );
1025                 exit( EXIT_FAILURE );
1026         }
1027
1028         if( ctrls ) {
1029                 print_ctrls( ctrls );
1030                 ldap_controls_free( ctrls );
1031         }
1032
1033         if ( includeufn ) {
1034                 if( ufn == NULL ) {
1035                         ufn = ldap_dn2ufn( dn );
1036                 }
1037                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1038         }
1039
1040         if( ufn != NULL ) ldap_memfree( ufn );
1041         ldap_memfree( dn );
1042
1043         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
1044                 a = ldap_next_attribute( ld, entry, ber ) )
1045         {
1046                 if ( attrsonly ) {
1047                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
1048
1049                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
1050                         for ( i = 0; bvals[i] != NULL; i++ ) {
1051                                 if ( vals2tmp > 1 || ( vals2tmp
1052                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
1053                                 {
1054                                         int tmpfd;
1055                                         /* write value to file */
1056                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1057                                                 tmpdir, a );
1058                                         tmpfp = NULL;
1059
1060                                         if ( mktemp( tmpfname ) == NULL ) {
1061                                                 perror( tmpfname );
1062                                                 continue;
1063                                         }
1064
1065                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
1066                                                 perror( tmpfname );
1067                                                 continue;
1068                                         }
1069
1070                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1071                                                 perror( tmpfname );
1072                                                 continue;
1073                                         }
1074
1075                                         if ( fwrite( bvals[ i ]->bv_val,
1076                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
1077                                         {
1078                                                 perror( tmpfname );
1079                                                 fclose( tmpfp );
1080                                                 continue;
1081                                         }
1082
1083                                         fclose( tmpfp );
1084
1085                                         sprintf( url, "%s%s", urlpre,
1086                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1087
1088                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
1089
1090                                 } else {
1091                                         write_ldif( LDIF_PUT_VALUE, a,
1092                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
1093                                 }
1094                         }
1095                         ber_bvecfree( bvals );
1096                 }
1097         }
1098
1099         if( ber != NULL ) {
1100                 ber_free( ber, 0 );
1101         }
1102 }
1103
1104 static void print_reference(
1105         LDAP *ld,
1106         LDAPMessage *reference )
1107 {
1108         int rc;
1109         char **refs = NULL;
1110         LDAPControl **ctrls;
1111
1112         if( ldif < 2 ) {
1113                 printf("# search reference\n");
1114         }
1115
1116         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1117
1118         if( rc != LDAP_SUCCESS ) {
1119                 ldap_perror(ld, "ldap_parse_reference");
1120                 exit( EXIT_FAILURE );
1121         }
1122
1123         if( refs ) {
1124                 int i;
1125                 for( i=0; refs[i] != NULL; i++ ) {
1126                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1127                                 "ref", refs[i], strlen(refs[i]) );
1128                 }
1129                 ber_memvfree( (void **) refs );
1130         }
1131
1132         if( ctrls ) {
1133                 print_ctrls( ctrls );
1134                 ldap_controls_free( ctrls );
1135         }
1136 }
1137
1138 static void print_extended(
1139         LDAP *ld,
1140         LDAPMessage *extended )
1141 {
1142         int rc;
1143         char *retoid = NULL;
1144         struct berval *retdata = NULL;
1145
1146         if( ldif < 2 ) {
1147                 printf("# extended result response\n");
1148         }
1149
1150         rc = ldap_parse_extended_result( ld, extended,
1151                 &retoid, &retdata, 0 );
1152
1153         if( rc != LDAP_SUCCESS ) {
1154                 ldap_perror(ld, "ldap_parse_extended_result");
1155                 exit( EXIT_FAILURE );
1156         }
1157
1158         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1159                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1160         ber_memfree( retoid );
1161
1162         if(retdata) {
1163                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1164                         "data", retdata->bv_val, retdata->bv_len );
1165                 ber_bvfree( retdata );
1166         }
1167
1168         print_result( ld, extended, 0 );
1169 }
1170
1171 static void print_partial(
1172         LDAP *ld,
1173         LDAPMessage *partial )
1174 {
1175         int rc;
1176         char *retoid = NULL;
1177         struct berval *retdata = NULL;
1178         LDAPControl **ctrls = NULL;
1179
1180         if( ldif < 2 ) {
1181                 printf("# extended partial response\n");
1182         }
1183
1184         rc = ldap_parse_extended_partial( ld, partial,
1185                 &retoid, &retdata, &ctrls, 0 );
1186
1187         if( rc != LDAP_SUCCESS ) {
1188                 ldap_perror(ld, "ldap_parse_extended_partial");
1189                 exit( EXIT_FAILURE );
1190         }
1191
1192         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1193                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1194
1195         ber_memfree( retoid );
1196
1197         if( retdata ) {
1198                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1199                         "data", 
1200                         retdata->bv_val, retdata->bv_len );
1201
1202                 ber_bvfree( retdata );
1203         }
1204
1205         if( ctrls ) {
1206                 print_ctrls( ctrls );
1207                 ldap_controls_free( ctrls );
1208         }
1209 }
1210
1211 static int print_result(
1212         LDAP *ld,
1213         LDAPMessage *result, int search )
1214 {
1215         char rst[BUFSIZ];
1216         int rc;
1217         int err;
1218         char *matcheddn = NULL;
1219         char *text = NULL;
1220         char **refs = NULL;
1221         LDAPControl **ctrls = NULL;
1222
1223         if( search ) {
1224                 if ( ldif < 2 ) {
1225                         printf("# search result\n");
1226                 }
1227                 if ( ldif < 1 ) {
1228                         printf("%s: %d\n", "search", ldap_msgid(result) );
1229                 }
1230         }
1231
1232         rc = ldap_parse_result( ld, result,
1233                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1234
1235         if( rc != LDAP_SUCCESS ) {
1236                 ldap_perror(ld, "ldap_parse_result");
1237                 exit( EXIT_FAILURE );
1238         }
1239
1240
1241         if( !ldif ) {
1242                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1243
1244         } else if ( err != LDAP_SUCCESS ) {
1245                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1246         }
1247
1248         if( matcheddn && *matcheddn ) {
1249                 if( !ldif ) {
1250                         write_ldif( LDIF_PUT_VALUE,
1251                                 "matchedDN", matcheddn, strlen(matcheddn) );
1252                 } else {
1253                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1254                 }
1255
1256                 ber_memfree( matcheddn );
1257         }
1258
1259         if( text && *text ) {
1260                 if( !ldif ) {
1261                         write_ldif( LDIF_PUT_TEXT, "text",
1262                                 text, strlen(text) );
1263                 } else {
1264                         fprintf( stderr, "Additional information: %s\n", text );
1265                 }
1266
1267                 ber_memfree( text );
1268         }
1269
1270         if( refs ) {
1271                 int i;
1272                 for( i=0; refs[i] != NULL; i++ ) {
1273                         if( !ldif ) {
1274                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1275                         } else {
1276                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1277                         }
1278                 }
1279
1280                 ber_memvfree( (void **) refs );
1281         }
1282
1283         if( ctrls ) {
1284                 print_ctrls( ctrls );
1285                 ldap_controls_free( ctrls );
1286         }
1287
1288         return err;
1289 }
1290
1291 void print_ctrls( LDAPControl **ctrls ) {
1292         int i;
1293         for(i=0; ctrls[i] != NULL; i++ ) {
1294                 /* control: OID criticality base64value */
1295                 struct berval *b64 = NULL;
1296                 ber_len_t len;
1297                 char *str;
1298                         
1299                 len = strlen( ctrls[i]->ldctl_oid );
1300
1301                 /* add enough for space after OID and the critical value itself */
1302                 len += ctrls[i]->ldctl_iscritical
1303                         ? sizeof("true") : sizeof("false");
1304
1305                 /* convert to base64 */
1306                 if( ctrls[i]->ldctl_value.bv_len ) {
1307                         b64 = ber_memalloc( sizeof(struct berval) );
1308                         
1309                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1310                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1311                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1312
1313                         b64->bv_len = lutil_b64_ntop(
1314                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1315                                 b64->bv_val, b64->bv_len );
1316                 }
1317
1318                 if( b64 ) {
1319                         len += 1 + b64->bv_len;
1320                 }
1321
1322                 str = malloc( len + 1 );
1323                 strcpy( str, ctrls[i]->ldctl_oid );
1324                 strcat( str, ctrls[i]->ldctl_iscritical
1325                         ? " true" : " false" );
1326
1327                 if( b64 ) {
1328                         strcat(str, " ");
1329                         strcat(str, b64->bv_val );
1330                 }
1331
1332                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1333                         "control", str, len );
1334
1335                 free( str );
1336                 ber_bvfree( b64 );
1337         }
1338 }
1339
1340 static int
1341 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1342 {
1343         char    *ldif;
1344
1345         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1346                 return( -1 );
1347         }
1348
1349         fputs( ldif, stdout );
1350         ber_memfree( ldif );
1351
1352         return( 0 );
1353 }