]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Improved but still broken client tools.
[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                 fprintf( stderr, "ldapsearch: ldap_search_ext: %s (%d)",
717                         ldap_err2string( rc ), rc );
718                 return( rc );
719         }
720
721         nresponses = nentries = nreferences = nextended = npartial = 0;
722
723         res = NULL;
724
725         while ((rc = ldap_result( ld, LDAP_RES_ANY,
726                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
727                 NULL, &res )) > 0 )
728         {
729                 if( sortattr ) {
730                         (void) ldap_sort_entries( ld, &res,
731                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
732                 }
733
734                 for ( msg = ldap_first_message( ld, res );
735                         msg != NULL;
736                         msg = ldap_next_message( ld, msg ) )
737                 {
738                         if( nresponses++ ) putchar('\n');
739
740                         switch( ldap_msgtype( msg ) ) {
741                         case LDAP_RES_SEARCH_ENTRY:
742                                 nentries++;
743                                 print_entry( ld, msg, attrsonly );
744                                 break;
745
746                         case LDAP_RES_SEARCH_REFERENCE:
747                                 nreferences++;
748                                 print_reference( ld, msg );
749                                 break;
750
751                         case LDAP_RES_EXTENDED:
752                                 nextended++;
753                                 print_extended( ld, msg );
754
755                                 if( ldap_msgid( msg ) == 0 ) {
756                                         /* unsolicited extended operation */
757                                         goto done;
758                                 }
759                                 break;
760
761                         case LDAP_RES_EXTENDED_PARTIAL:
762                                 npartial++;
763                                 print_partial( ld, msg );
764                                 break;
765
766                         case LDAP_RES_SEARCH_RESULT:
767                                 rc = print_result( ld, msg, 1 );
768                                 goto done;
769                         }
770                 }
771
772                 ldap_msgfree( res );
773         }
774
775         if ( rc == -1 ) {
776                 ldap_perror( ld, "ldap_result" );
777                 return( rc );
778         }
779
780 done:
781         if ( ldif < 2 ) {
782                 printf( "\n# numResponses: %d\n", nresponses );
783                 if( nentries ) printf( "# numEntries: %d\n", nentries );
784                 if( nextended ) printf( "# numExtended: %d\n", nextended );
785                 if( npartial ) printf( "# numPartial: %d\n", npartial );
786                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
787         }
788
789         return( rc );
790 }
791
792 static void
793 print_entry(
794         LDAP    *ld,
795         LDAPMessage     *entry,
796         int             attrsonly)
797 {
798         char            *a, *dn, *ufn;
799         char    tmpfname[ 256 ];
800         char    url[ 256 ];
801         int                     i, rc;
802         BerElement              *ber = NULL;
803         struct berval   **bvals;
804         LDAPControl **ctrls = NULL;
805         FILE            *tmpfp;
806
807         dn = ldap_get_dn( ld, entry );
808         ufn = NULL;
809
810         if ( ldif < 2 ) {
811                 ufn = ldap_dn2ufn( dn );
812                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
813         }
814         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
815
816         rc = ldap_get_entry_controls( ld, entry, &ctrls );
817
818         if( rc != LDAP_SUCCESS ) {
819                 fprintf(stderr, "print_entry: %d\n", rc );
820                 ldap_perror( ld, "ldap_get_entry_controls" );
821                 exit( EXIT_FAILURE );
822         }
823
824         if( ctrls ) {
825                 print_ctrls( ctrls );
826                 ldap_controls_free( ctrls );
827         }
828
829         if ( includeufn ) {
830                 if( ufn == NULL ) {
831                         ufn = ldap_dn2ufn( dn );
832                 }
833                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
834         }
835
836         if( ufn != NULL ) ldap_memfree( ufn );
837         ldap_memfree( dn );
838
839         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
840                 a = ldap_next_attribute( ld, entry, ber ) )
841         {
842                 if ( attrsonly ) {
843                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
844
845                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
846                         for ( i = 0; bvals[i] != NULL; i++ ) {
847                                 if ( vals2tmp > 1 || ( vals2tmp
848                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
849                                 {
850                                         int tmpfd;
851                                         /* write value to file */
852                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
853                                                 tmpdir, a );
854                                         tmpfp = NULL;
855
856                                         if ( mktemp( tmpfname ) == NULL ) {
857                                                 perror( tmpfname );
858                                                 continue;
859                                         }
860
861                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
862                                                 perror( tmpfname );
863                                                 continue;
864                                         }
865
866                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
867                                                 perror( tmpfname );
868                                                 continue;
869                                         }
870
871                                         if ( fwrite( bvals[ i ]->bv_val,
872                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
873                                         {
874                                                 perror( tmpfname );
875                                                 fclose( tmpfp );
876                                                 continue;
877                                         }
878
879                                         fclose( tmpfp );
880
881                                         sprintf( url, "%s%s", urlpre,
882                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
883
884                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
885
886                                 } else {
887                                         write_ldif( LDIF_PUT_VALUE, a,
888                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
889                                 }
890                         }
891                         ber_bvecfree( bvals );
892                 }
893         }
894
895         if( ber != NULL ) {
896                 ber_free( ber, 0 );
897         }
898 }
899
900 static void print_reference(
901         LDAP *ld,
902         LDAPMessage *reference )
903 {
904         int rc;
905         char **refs = NULL;
906         LDAPControl **ctrls;
907
908         if( ldif < 2 ) {
909                 printf("# search reference\n");
910         }
911
912         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
913
914         if( rc != LDAP_SUCCESS ) {
915                 ldap_perror(ld, "ldap_parse_reference");
916                 exit( EXIT_FAILURE );
917         }
918
919         if( refs ) {
920                 int i;
921                 for( i=0; refs[i] != NULL; i++ ) {
922                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
923                                 "ref", refs[i], strlen(refs[i]) );
924                 }
925                 ber_memvfree( (void **) refs );
926         }
927
928         if( ctrls ) {
929                 print_ctrls( ctrls );
930                 ldap_controls_free( ctrls );
931         }
932 }
933
934 static void print_extended(
935         LDAP *ld,
936         LDAPMessage *extended )
937 {
938         int rc;
939         char *retoid = NULL;
940         struct berval *retdata = NULL;
941
942         if( ldif < 2 ) {
943                 printf("# extended result response\n");
944         }
945
946         rc = ldap_parse_extended_result( ld, extended,
947                 &retoid, &retdata, 0 );
948
949         if( rc != LDAP_SUCCESS ) {
950                 ldap_perror(ld, "ldap_parse_extended_result");
951                 exit( EXIT_FAILURE );
952         }
953
954         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
955                 "extended", retoid, retoid ? strlen(retoid) : 0 );
956         ber_memfree( retoid );
957
958         if(retdata) {
959                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
960                         "data", retdata->bv_val, retdata->bv_len );
961                 ber_bvfree( retdata );
962         }
963
964         print_result( ld, extended, 0 );
965 }
966
967 static void print_partial(
968         LDAP *ld,
969         LDAPMessage *partial )
970 {
971         int rc;
972         char *retoid = NULL;
973         struct berval *retdata = NULL;
974         LDAPControl **ctrls = NULL;
975
976         if( ldif < 2 ) {
977                 printf("# extended partial response\n");
978         }
979
980         rc = ldap_parse_extended_partial( ld, partial,
981                 &retoid, &retdata, &ctrls, 0 );
982
983         if( rc != LDAP_SUCCESS ) {
984                 ldap_perror(ld, "ldap_parse_extended_partial");
985                 exit( EXIT_FAILURE );
986         }
987
988         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
989                 "partial", retoid, retoid ? strlen(retoid) : 0 );
990
991         ber_memfree( retoid );
992
993         if( retdata ) {
994                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
995                         "data", 
996                         retdata->bv_val, retdata->bv_len );
997
998                 ber_bvfree( retdata );
999         }
1000
1001         if( ctrls ) {
1002                 print_ctrls( ctrls );
1003                 ldap_controls_free( ctrls );
1004         }
1005 }
1006
1007 static int print_result(
1008         LDAP *ld,
1009         LDAPMessage *result, int search )
1010 {
1011         char rst[BUFSIZ];
1012         int rc;
1013         int err;
1014         char *matcheddn = NULL;
1015         char *text = NULL;
1016         char **refs = NULL;
1017         LDAPControl **ctrls = NULL;
1018
1019         if( search ) {
1020                 if ( ldif < 2 ) {
1021                         printf("# search result\n");
1022                 }
1023                 if ( ldif < 1 ) {
1024                         printf("%s: %d\n", "search", ldap_msgid(result) );
1025                 }
1026         }
1027
1028         rc = ldap_parse_result( ld, result,
1029                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1030
1031         if( rc != LDAP_SUCCESS ) {
1032                 ldap_perror(ld, "ldap_parse_result");
1033                 exit( EXIT_FAILURE );
1034         }
1035
1036
1037         if( !ldif ) {
1038                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1039
1040         } else if ( err != LDAP_SUCCESS ) {
1041                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1042         }
1043
1044         if( matcheddn && *matcheddn ) {
1045                 if( !ldif ) {
1046                         write_ldif( LDIF_PUT_VALUE,
1047                                 "matchedDN", matcheddn, strlen(matcheddn) );
1048                 } else {
1049                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1050                 }
1051
1052                 ber_memfree( matcheddn );
1053         }
1054
1055         if( text && *text ) {
1056                 if( !ldif ) {
1057                         write_ldif( LDIF_PUT_TEXT, "text",
1058                                 text, strlen(text) );
1059                 } else {
1060                         fprintf( stderr, "Additional information: %s\n", text );
1061                 }
1062
1063                 ber_memfree( text );
1064         }
1065
1066         if( refs ) {
1067                 int i;
1068                 for( i=0; refs[i] != NULL; i++ ) {
1069                         if( !ldif ) {
1070                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1071                         } else {
1072                                 fprintf( stderr, "Referral: %s", refs[i] );
1073                         }
1074                 }
1075
1076                 ber_memvfree( (void **) refs );
1077         }
1078
1079         if( ctrls ) {
1080                 print_ctrls( ctrls );
1081                 ldap_controls_free( ctrls );
1082         }
1083
1084         return err;
1085 }
1086
1087 void print_ctrls( LDAPControl **ctrls ) {
1088         int i;
1089         for(i=0; ctrls[i] != NULL; i++ ) {
1090                 /* control: OID criticality base64value */
1091                 struct berval *b64 = NULL;
1092                 ber_len_t len;
1093                 char *str;
1094                         
1095                 len = strlen( ctrls[i]->ldctl_oid );
1096
1097                 /* add enough for space after OID and the critical value itself */
1098                 len += ctrls[i]->ldctl_iscritical
1099                         ? sizeof("true") : sizeof("false");
1100
1101                 /* convert to base64 */
1102                 if( ctrls[i]->ldctl_value.bv_len ) {
1103                         b64 = ber_memalloc( sizeof(struct berval) );
1104                         
1105                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1106                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1107                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1108
1109                         b64->bv_len = lutil_b64_ntop(
1110                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1111                                 b64->bv_val, b64->bv_len );
1112                 }
1113
1114                 if( b64 ) {
1115                         len += 1 + b64->bv_len;
1116                 }
1117
1118                 str = malloc( len + 1 );
1119                 strcpy( str, ctrls[i]->ldctl_oid );
1120                 strcat( str, ctrls[i]->ldctl_iscritical
1121                         ? " true" : " false" );
1122
1123                 if( b64 ) {
1124                         strcat(str, " ");
1125                         strcat(str, b64->bv_val );
1126                 }
1127
1128                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1129                         "control", str, len );
1130
1131                 free( str );
1132                 ber_bvfree( b64 );
1133         }
1134 }
1135
1136 static int
1137 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1138 {
1139         char    *ldif;
1140
1141         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1142                 return( -1 );
1143         }
1144
1145         fputs( ldif, stdout );
1146         ber_memfree( ldif );
1147
1148         return( 0 );
1149 }