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