]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
e07b3ff83866dbb043de7020918fd7d6b44729d2
[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                 authmethod = LDAP_AUTH_SASL;
468         }
469
470         if (( argc - optind < 1 ) ||
471                 ( strchr( argv[optind], '=' ) == NULL ) )
472         {
473                 filtpattern = "(objectclass=*)";
474         } else {
475                 filtpattern = strdup( argv[optind++] );
476         }
477
478         if ( argv[optind] == NULL ) {
479                 attrs = NULL;
480         } else if ( sortattr == NULL || *sortattr == '\0' ) {
481                 attrs = &argv[optind];
482         }
483
484         if ( infile != NULL ) {
485                 if ( infile[0] == '-' && infile[1] == '\0' ) {
486                         fp = stdin;
487                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
488                         perror( infile );
489                         return EXIT_FAILURE;
490                 }
491         }
492
493         if( tmpdir == NULL
494                 && (tmpdir = getenv("TMPDIR")) == NULL
495                 && (tmpdir = getenv("TMP")) == NULL
496                 && (tmpdir = getenv("TEMP")) == NULL )
497         {
498                 tmpdir = LDAP_TMPDIR;
499         }
500
501         if( urlpre == NULL ) {
502                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
503
504                 if( urlpre == NULL ) {
505                         perror( "malloc" );
506                         return EXIT_FAILURE;
507                 }
508
509                 sprintf( urlpre, "file:///%s/",
510                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
511
512                 /* urlpre should be URLized.... */
513         }
514
515         if ( debug ) {
516                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
517                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
518                 }
519                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
520                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
521                 }
522                 ldif_debug = debug;
523         }
524
525 #ifdef SIGPIPE
526         (void) SIGNAL( SIGPIPE, SIG_IGN );
527 #endif
528
529         if ( verbose ) {
530                 fprintf( stderr,
531                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
532                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
533                         ldapport );
534         }
535
536         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
537                 perror( "ldap_init" );
538                 return EXIT_FAILURE;
539         }
540
541         if (deref != -1 &&
542                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
543         {
544                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
545                 return EXIT_FAILURE;
546         }
547         if (timelimit != -1 &&
548                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
549         {
550                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
551                 return EXIT_FAILURE;
552         }
553         if (sizelimit != -1 &&
554                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
555         {
556                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
557                 return EXIT_FAILURE;
558         }
559
560         /* referrals */
561         if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
562                 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
563         {
564                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
565                         referrals ? "on" : "off" );
566                 return EXIT_FAILURE;
567         }
568
569         if (version == -1 ) {
570                 version = 3;
571         }
572
573         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
574                 != LDAP_OPT_SUCCESS )
575         {
576                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
577                         version );
578                 return EXIT_FAILURE;
579         }
580
581         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
582                 if ( use_tls > 1 ) {
583                         ldap_perror( ld, "ldap_start_tls" );
584                         return EXIT_FAILURE;
585                 }
586                 fprintf( stderr, "WARNING: could not start TLS\n" );
587         }
588
589         if (want_bindpw) {
590                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
591                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
592         }
593
594         if ( authmethod == LDAP_AUTH_SASL ) {
595 #ifdef HAVE_CYRUS_SASL
596                 if( sasl_secprops != NULL ) {
597                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
598                                 (void *) sasl_secprops );
599                         
600                         if( rc != LDAP_OPT_SUCCESS ) {
601                                 fprintf( stderr,
602                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
603                                         sasl_secprops );
604                                 return( EXIT_FAILURE );
605                         }
606                 }
607                 
608                 rc = ldap_sasl_interactive_bind_s( ld, binddn,
609                                 sasl_mech, NULL, NULL, lutil_sasl_interact );
610
611                 if( rc != LDAP_SUCCESS ) {
612                         ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
613                         return( EXIT_FAILURE );
614                 }
615 #else
616                 fprintf( stderr, "%s was not compiled with SASL support\n",
617                         argv[0] );
618                 return( EXIT_FAILURE );
619 #endif
620         } else {
621                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
622                                 != LDAP_SUCCESS ) {
623                         ldap_perror( ld, "ldap_bind" );
624                         return( EXIT_FAILURE );
625                 }
626         }
627
628         if ( manageDSAit ) {
629                 int err;
630                 LDAPControl c;
631                 LDAPControl *ctrls[2];
632                 ctrls[0] = &c;
633                 ctrls[1] = NULL;
634
635                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
636                 c.ldctl_value.bv_val = NULL;
637                 c.ldctl_value.bv_len = 0;
638                 c.ldctl_iscritical = manageDSAit > 1;
639
640                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
641
642                 if( err != LDAP_OPT_SUCCESS ) {
643                         fprintf( stderr, "Could not set ManageDSAit %scontrol\n",
644                                 c.ldctl_iscritical ? "critical " : "" );
645                         if( c.ldctl_iscritical ) {
646                                 exit( EXIT_FAILURE );
647                         }
648                 }
649         }
650
651         if ( verbose ) {
652                 fprintf( stderr, "filter%s: %s\nrequesting: ",
653                         infile != NULL ? " pattern" : "",
654                         filtpattern );
655
656                 if ( attrs == NULL ) {
657                         fprintf( stderr, "ALL" );
658                 } else {
659                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
660                                 fprintf( stderr, "%s ", attrs[ i ] );
661                         }
662                 }
663                 fprintf( stderr, "\n" );
664         }
665
666         if (ldif < 3 ) {
667                 printf( "version: %d\n\n", ldif ? 1 : 2 );
668         }
669
670         if (ldif < 2 ) {
671                 printf( "#\n# filter%s: %s\n# requesting: ",
672                         infile != NULL ? " pattern" : "",
673                         filtpattern );
674
675                 if ( attrs == NULL ) {
676                         printf( "ALL" );
677                 } else {
678                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
679                                 printf( "%s ", attrs[ i ] );
680                         }
681                 }
682
683                 if ( manageDSAit ) {
684                         printf("\n# with manageDSAit %scontrol",
685                                 manageDSAit > 1 ? "critical " : "" );
686                 }
687
688                 printf( "\n#\n\n" );
689         }
690
691         if ( infile == NULL ) {
692                 rc = dosearch( ld, base, scope, NULL, filtpattern,
693                         attrs, attrsonly, NULL, NULL, NULL, -1 );
694
695         } else {
696                 rc = 0;
697                 first = 1;
698                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
699                         line[ strlen( line ) - 1 ] = '\0';
700                         if ( !first ) {
701                                 putchar( '\n' );
702                         } else {
703                                 first = 0;
704                         }
705                         rc = dosearch( ld, base, scope, filtpattern, line,
706                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
707                 }
708                 if ( fp != stdin ) {
709                         fclose( fp );
710                 }
711         }
712
713         ldap_unbind( ld );
714         return( rc );
715 }
716
717
718 static int dosearch(
719         LDAP    *ld,
720         char    *base,
721         int             scope,
722         char    *filtpatt,
723         char    *value,
724         char    **attrs,
725         int             attrsonly,
726         LDAPControl **sctrls,
727         LDAPControl **cctrls,
728         struct timeval *timelimit,
729         int sizelimit )
730 {
731         char            filter[ BUFSIZ ];
732         int                     rc, first;
733         int                     nresponses;
734         int                     nentries;
735         int                     nreferences;
736         int                     nextended;
737         int                     npartial;
738         LDAPMessage             *res, *msg;
739         ber_int_t       msgid;
740
741         if( filtpatt != NULL ) {
742                 sprintf( filter, filtpatt, value );
743
744                 if ( verbose ) {
745                         fprintf( stderr, "filter is: (%s)\n", filter );
746                 }
747
748                 if( ldif < 2 ) {
749                         printf( "#\n# filter: %s\n#\n", filter );
750                 }
751
752         } else {
753                 sprintf( filter, "%s", value );
754         }
755
756         if ( not ) {
757                 return LDAP_SUCCESS;
758         }
759
760         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
761                 sctrls, cctrls, timelimit, sizelimit, &msgid );
762
763         if( rc != LDAP_SUCCESS ) {
764                 fprintf( stderr, "ldapsearch: ldap_search_ext: %s (%d)\n",
765                         ldap_err2string( rc ), rc );
766                 return( rc );
767         }
768
769         nresponses = nentries = nreferences = nextended = npartial = 0;
770
771         res = NULL;
772
773         while ((rc = ldap_result( ld, LDAP_RES_ANY,
774                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
775                 NULL, &res )) > 0 )
776         {
777                 if( sortattr ) {
778                         (void) ldap_sort_entries( ld, &res,
779                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
780                 }
781
782                 for ( msg = ldap_first_message( ld, res );
783                         msg != NULL;
784                         msg = ldap_next_message( ld, msg ) )
785                 {
786                         if( nresponses++ ) putchar('\n');
787
788                         switch( ldap_msgtype( msg ) ) {
789                         case LDAP_RES_SEARCH_ENTRY:
790                                 nentries++;
791                                 print_entry( ld, msg, attrsonly );
792                                 break;
793
794                         case LDAP_RES_SEARCH_REFERENCE:
795                                 nreferences++;
796                                 print_reference( ld, msg );
797                                 break;
798
799                         case LDAP_RES_EXTENDED:
800                                 nextended++;
801                                 print_extended( ld, msg );
802
803                                 if( ldap_msgid( msg ) == 0 ) {
804                                         /* unsolicited extended operation */
805                                         goto done;
806                                 }
807                                 break;
808
809                         case LDAP_RES_EXTENDED_PARTIAL:
810                                 npartial++;
811                                 print_partial( ld, msg );
812                                 break;
813
814                         case LDAP_RES_SEARCH_RESULT:
815                                 rc = print_result( ld, msg, 1 );
816                                 goto done;
817                         }
818                 }
819
820                 ldap_msgfree( res );
821         }
822
823         if ( rc == -1 ) {
824                 ldap_perror( ld, "ldap_result" );
825                 return( rc );
826         }
827
828 done:
829         if ( ldif < 2 ) {
830                 printf( "\n# numResponses: %d\n", nresponses );
831                 if( nentries ) printf( "# numEntries: %d\n", nentries );
832                 if( nextended ) printf( "# numExtended: %d\n", nextended );
833                 if( npartial ) printf( "# numPartial: %d\n", npartial );
834                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
835         }
836
837         return( rc );
838 }
839
840 static void
841 print_entry(
842         LDAP    *ld,
843         LDAPMessage     *entry,
844         int             attrsonly)
845 {
846         char            *a, *dn, *ufn;
847         char    tmpfname[ 256 ];
848         char    url[ 256 ];
849         int                     i, rc;
850         BerElement              *ber = NULL;
851         struct berval   **bvals;
852         LDAPControl **ctrls = NULL;
853         FILE            *tmpfp;
854
855         dn = ldap_get_dn( ld, entry );
856         ufn = NULL;
857
858         if ( ldif < 2 ) {
859                 ufn = ldap_dn2ufn( dn );
860                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
861         }
862         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
863
864         rc = ldap_get_entry_controls( ld, entry, &ctrls );
865
866         if( rc != LDAP_SUCCESS ) {
867                 fprintf(stderr, "print_entry: %d\n", rc );
868                 ldap_perror( ld, "ldap_get_entry_controls" );
869                 exit( EXIT_FAILURE );
870         }
871
872         if( ctrls ) {
873                 print_ctrls( ctrls );
874                 ldap_controls_free( ctrls );
875         }
876
877         if ( includeufn ) {
878                 if( ufn == NULL ) {
879                         ufn = ldap_dn2ufn( dn );
880                 }
881                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
882         }
883
884         if( ufn != NULL ) ldap_memfree( ufn );
885         ldap_memfree( dn );
886
887         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
888                 a = ldap_next_attribute( ld, entry, ber ) )
889         {
890                 if ( attrsonly ) {
891                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
892
893                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
894                         for ( i = 0; bvals[i] != NULL; i++ ) {
895                                 if ( vals2tmp > 1 || ( vals2tmp
896                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
897                                 {
898                                         int tmpfd;
899                                         /* write value to file */
900                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
901                                                 tmpdir, a );
902                                         tmpfp = NULL;
903
904                                         if ( mktemp( tmpfname ) == NULL ) {
905                                                 perror( tmpfname );
906                                                 continue;
907                                         }
908
909                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
910                                                 perror( tmpfname );
911                                                 continue;
912                                         }
913
914                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
915                                                 perror( tmpfname );
916                                                 continue;
917                                         }
918
919                                         if ( fwrite( bvals[ i ]->bv_val,
920                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
921                                         {
922                                                 perror( tmpfname );
923                                                 fclose( tmpfp );
924                                                 continue;
925                                         }
926
927                                         fclose( tmpfp );
928
929                                         sprintf( url, "%s%s", urlpre,
930                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
931
932                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
933
934                                 } else {
935                                         write_ldif( LDIF_PUT_VALUE, a,
936                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
937                                 }
938                         }
939                         ber_bvecfree( bvals );
940                 }
941         }
942
943         if( ber != NULL ) {
944                 ber_free( ber, 0 );
945         }
946 }
947
948 static void print_reference(
949         LDAP *ld,
950         LDAPMessage *reference )
951 {
952         int rc;
953         char **refs = NULL;
954         LDAPControl **ctrls;
955
956         if( ldif < 2 ) {
957                 printf("# search reference\n");
958         }
959
960         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
961
962         if( rc != LDAP_SUCCESS ) {
963                 ldap_perror(ld, "ldap_parse_reference");
964                 exit( EXIT_FAILURE );
965         }
966
967         if( refs ) {
968                 int i;
969                 for( i=0; refs[i] != NULL; i++ ) {
970                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
971                                 "ref", refs[i], strlen(refs[i]) );
972                 }
973                 ber_memvfree( (void **) refs );
974         }
975
976         if( ctrls ) {
977                 print_ctrls( ctrls );
978                 ldap_controls_free( ctrls );
979         }
980 }
981
982 static void print_extended(
983         LDAP *ld,
984         LDAPMessage *extended )
985 {
986         int rc;
987         char *retoid = NULL;
988         struct berval *retdata = NULL;
989
990         if( ldif < 2 ) {
991                 printf("# extended result response\n");
992         }
993
994         rc = ldap_parse_extended_result( ld, extended,
995                 &retoid, &retdata, 0 );
996
997         if( rc != LDAP_SUCCESS ) {
998                 ldap_perror(ld, "ldap_parse_extended_result");
999                 exit( EXIT_FAILURE );
1000         }
1001
1002         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1003                 "extended", retoid, retoid ? strlen(retoid) : 0 );
1004         ber_memfree( retoid );
1005
1006         if(retdata) {
1007                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1008                         "data", retdata->bv_val, retdata->bv_len );
1009                 ber_bvfree( retdata );
1010         }
1011
1012         print_result( ld, extended, 0 );
1013 }
1014
1015 static void print_partial(
1016         LDAP *ld,
1017         LDAPMessage *partial )
1018 {
1019         int rc;
1020         char *retoid = NULL;
1021         struct berval *retdata = NULL;
1022         LDAPControl **ctrls = NULL;
1023
1024         if( ldif < 2 ) {
1025                 printf("# extended partial response\n");
1026         }
1027
1028         rc = ldap_parse_extended_partial( ld, partial,
1029                 &retoid, &retdata, &ctrls, 0 );
1030
1031         if( rc != LDAP_SUCCESS ) {
1032                 ldap_perror(ld, "ldap_parse_extended_partial");
1033                 exit( EXIT_FAILURE );
1034         }
1035
1036         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1037                 "partial", retoid, retoid ? strlen(retoid) : 0 );
1038
1039         ber_memfree( retoid );
1040
1041         if( retdata ) {
1042                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1043                         "data", 
1044                         retdata->bv_val, retdata->bv_len );
1045
1046                 ber_bvfree( retdata );
1047         }
1048
1049         if( ctrls ) {
1050                 print_ctrls( ctrls );
1051                 ldap_controls_free( ctrls );
1052         }
1053 }
1054
1055 static int print_result(
1056         LDAP *ld,
1057         LDAPMessage *result, int search )
1058 {
1059         char rst[BUFSIZ];
1060         int rc;
1061         int err;
1062         char *matcheddn = NULL;
1063         char *text = NULL;
1064         char **refs = NULL;
1065         LDAPControl **ctrls = NULL;
1066
1067         if( search ) {
1068                 if ( ldif < 2 ) {
1069                         printf("# search result\n");
1070                 }
1071                 if ( ldif < 1 ) {
1072                         printf("%s: %d\n", "search", ldap_msgid(result) );
1073                 }
1074         }
1075
1076         rc = ldap_parse_result( ld, result,
1077                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1078
1079         if( rc != LDAP_SUCCESS ) {
1080                 ldap_perror(ld, "ldap_parse_result");
1081                 exit( EXIT_FAILURE );
1082         }
1083
1084
1085         if( !ldif ) {
1086                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1087
1088         } else if ( err != LDAP_SUCCESS ) {
1089                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1090         }
1091
1092         if( matcheddn && *matcheddn ) {
1093                 if( !ldif ) {
1094                         write_ldif( LDIF_PUT_VALUE,
1095                                 "matchedDN", matcheddn, strlen(matcheddn) );
1096                 } else {
1097                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1098                 }
1099
1100                 ber_memfree( matcheddn );
1101         }
1102
1103         if( text && *text ) {
1104                 if( !ldif ) {
1105                         write_ldif( LDIF_PUT_TEXT, "text",
1106                                 text, strlen(text) );
1107                 } else {
1108                         fprintf( stderr, "Additional information: %s\n", text );
1109                 }
1110
1111                 ber_memfree( text );
1112         }
1113
1114         if( refs ) {
1115                 int i;
1116                 for( i=0; refs[i] != NULL; i++ ) {
1117                         if( !ldif ) {
1118                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1119                         } else {
1120                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1121                         }
1122                 }
1123
1124                 ber_memvfree( (void **) refs );
1125         }
1126
1127         if( ctrls ) {
1128                 print_ctrls( ctrls );
1129                 ldap_controls_free( ctrls );
1130         }
1131
1132         return err;
1133 }
1134
1135 void print_ctrls( LDAPControl **ctrls ) {
1136         int i;
1137         for(i=0; ctrls[i] != NULL; i++ ) {
1138                 /* control: OID criticality base64value */
1139                 struct berval *b64 = NULL;
1140                 ber_len_t len;
1141                 char *str;
1142                         
1143                 len = strlen( ctrls[i]->ldctl_oid );
1144
1145                 /* add enough for space after OID and the critical value itself */
1146                 len += ctrls[i]->ldctl_iscritical
1147                         ? sizeof("true") : sizeof("false");
1148
1149                 /* convert to base64 */
1150                 if( ctrls[i]->ldctl_value.bv_len ) {
1151                         b64 = ber_memalloc( sizeof(struct berval) );
1152                         
1153                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1154                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1155                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1156
1157                         b64->bv_len = lutil_b64_ntop(
1158                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1159                                 b64->bv_val, b64->bv_len );
1160                 }
1161
1162                 if( b64 ) {
1163                         len += 1 + b64->bv_len;
1164                 }
1165
1166                 str = malloc( len + 1 );
1167                 strcpy( str, ctrls[i]->ldctl_oid );
1168                 strcat( str, ctrls[i]->ldctl_iscritical
1169                         ? " true" : " false" );
1170
1171                 if( b64 ) {
1172                         strcat(str, " ");
1173                         strcat(str, b64->bv_val );
1174                 }
1175
1176                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1177                         "control", str, len );
1178
1179                 free( str );
1180                 ber_bvfree( b64 );
1181         }
1182 }
1183
1184 static int
1185 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1186 {
1187         char    *ldif;
1188
1189         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1190                 return( -1 );
1191         }
1192
1193         fputs( ldif, stdout );
1194         ber_memfree( ldif );
1195
1196         return( 0 );
1197 }