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