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