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