]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Added -llber 'N' ber_printf format which inserts a NULL if
[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 "ldap_defaults.h"
34
35 static void
36 usage( const char *s )
37 {
38         fprintf( stderr,
39 "usage: %s [options] filter [attributes...]\nwhere:\n"
40 "       filter\tRFC-1558 compliant LDAP search filter\n"
41 "       attributes\twhitespace-separated list of attributes to retrieve\n"
42 "\t\t1.1                -- no attributes\n"
43 "\t\t*            -- all user attributes\n"
44 "\t\t+            -- all operational attributes\n"
45 "\t\tempty list -- all non-operational attributes\n"
46 "options:\n"
47 "       -a deref\tone of `never', `always', `search', or `find' (alias\n"
48 "               \tdereferencing)\n"
49 "       -A\t\tretrieve attribute names only (no values)\n"
50 "       -b basedn\tbase dn for search\n"
51 "       -d level\tset LDAP debugging level to `level'\n"
52 "       -D binddn\tbind DN\n"
53 "       -E\t\trequest SASL privacy (-EE to make it critical)\n"
54 "       -f file\t\tperform sequence of searches listed in `file'\n"
55 "       -h host\t\tLDAP server\n"
56 "       -I\t\trequest SASL integrity checking (-II to make it\n"
57 "               \tcritical)\n"
58 "       -k\t\tuse Kerberos authentication\n"
59 "       -K\t\tlike -k, but do only step 1 of the Kerberos bind\n"
60 "       -l limit\ttime limit (in seconds) for search\n"
61 "       -L\t\tprint entries in LDIF format (default)\n"
62 "       -LL\t\tprint entries in LDIF format without comments\n"
63 "       -LLL\t\tprint entries in LDIF format without comments and\n"
64 "               \tversion\n"
65 "       -M\t\tenable Manage DSA IT control (-MM to make critical)\n"
66 "       -n\t\tshow what would be done but don't actually search\n"
67 "       -p port\t\tport on LDAP server\n"
68 "       -P version\tprocotol version (2 or 3)\n"
69 "       -R\t\tdo not automatically follow referrals\n"
70 "       -s scope\tone of base, one, or sub (search scope)\n"
71 "       -S attr\t\tsort the results by attribute `attr'\n"
72 "       -t\t\twrite binary values to files in TMPDIR\n"
73 "       -tt\t\twrite all values to files in TMPDIR\n"
74 "       -T path\t\twrite files to directory specified by path (default:\n"
75 "               \t\"/tmp\")\n"
76 "       -u\t\tinclude User Friendly entry names in the output\n"
77 "       -U user\t\tSASL authentication identity (username)\n"
78 "       -v\t\trun in verbose mode (diagnostics to standard output)\n"
79 "       -V prefix\tURL prefix for files (default: \"file://tmp/\")\n"
80 "       -w passwd\tbind passwd (for simple authentication)\n"
81 "       -W\t\tprompt for bind passwd\n"
82 "       -X id\t\tSASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
83 "       -Y mech\t\tSASL mechanism\n"
84 "       -z limit\tsize limit (in entries) for search\n"
85 "       -Z\t\tissue Start TLS request (-ZZ to require successful response)\n"
86 ,               s );
87
88         exit( EXIT_FAILURE );
89 }
90
91 static void print_extended(
92         LDAP *ld,
93         LDAPMessage *extended );
94
95 static void print_partial(
96         LDAP *ld,
97         LDAPMessage *partial );
98
99 static void print_reference(
100         LDAP *ld,
101         LDAPMessage *reference );
102
103 static void print_entry LDAP_P((
104         LDAP    *ld,
105         LDAPMessage     *entry,
106         int             attrsonly));
107
108 static int write_ldif LDAP_P((
109         int type,
110         char *name,
111         char *value,
112         ber_len_t vallen ));
113
114 static int dosearch LDAP_P((
115         LDAP    *ld,
116         char    *base,
117         int             scope,
118         char    **attrs,
119         int             attrsonly,
120         char    *filtpatt,
121         char    *value));
122
123 #define TMPDIR "/tmp"
124 #define URLPRE "file:/tmp/"
125
126 static char *tmpdir = NULL;
127 static char *urlpre = NULL;
128
129 static char     *binddn = NULL;
130 static struct berval passwd = { 0, NULL };
131 static char     *base = NULL;
132 static char     *ldaphost = NULL;
133 static int      ldapport = 0;
134 #ifdef HAVE_CYRUS_SASL
135 static char     *sasl_authc_id = NULL;
136 static char     *sasl_authz_id = NULL;
137 static char     *sasl_mech = NULL;
138 static int      sasl_integrity = 0;
139 static int      sasl_privacy = 0;
140 #endif
141 static int      use_tls = 0;
142 static char     *sortattr = NULL;
143 static int      skipsortattr = 0;
144 static int      verbose, not, includeufn, vals2tmp, ldif;
145
146 int
147 main( int argc, char **argv )
148 {
149         char            *infile, *filtpattern, **attrs, line[ BUFSIZ ];
150         FILE            *fp = NULL;
151         int                     rc, i, first, scope, deref, attrsonly, manageDSAit;
152         int                     referrals, timelimit, sizelimit, debug;
153         int             authmethod, version, want_bindpw;
154         LDAP            *ld;
155
156         infile = NULL;
157         debug = verbose = not = vals2tmp =
158                 attrsonly = manageDSAit = ldif = want_bindpw = 0;
159
160         deref = sizelimit = timelimit = version = -1;
161
162         /* default should be off */
163         referrals = 1;
164
165         scope = LDAP_SCOPE_SUBTREE;
166         authmethod = LDAP_AUTH_SIMPLE;
167
168         while (( i = getopt( argc, argv,
169                 "Aa:b:D:d:Ef:h:IKkLl:MnP:p:RS:s:T:tU:uV:vWw:X:Y:Zz:")) != EOF )
170         {
171         switch( i ) {
172         case 'n':       /* do nothing */
173                 ++not;
174                 break;
175         case 'v':       /* verbose mode */
176                 ++verbose;
177                 break;
178         case 'd':
179                 debug |= atoi( optarg );
180                 break;
181         case 'k':       /* use kerberos bind */
182 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
183                 authmethod = LDAP_AUTH_KRBV4;
184 #else
185                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
186                 return( EXIT_FAILURE );
187 #endif
188                 break;
189         case 'K':       /* use kerberos bind, 1st part only */
190 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
191                 authmethod = LDAP_AUTH_KRBV41;
192 #else
193                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
194                 return( EXIT_FAILURE );
195 #endif
196                 break;
197                 break;
198         case 'u':       /* include UFN */
199                 ++includeufn;
200                 break;
201         case 't':       /* write attribute values to /tmp files */
202                 ++vals2tmp;
203                 break;
204         case 'M':
205                 /* enable Manage DSA IT */
206                 manageDSAit++;
207                 break;
208         case 'R':       /* don't automatically chase referrals */
209                 referrals = 0;
210                 break;
211         case 'A':       /* retrieve attribute names only -- no values */
212                 ++attrsonly;
213                 break;
214         case 'L':       /* print entries in LDIF format */
215                 ++ldif;
216                 break;
217
218         case 's':       /* search scope */
219                 if ( strcasecmp( optarg, "base" ) == 0 ) {
220                 scope = LDAP_SCOPE_BASE;
221                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
222                 scope = LDAP_SCOPE_ONELEVEL;
223                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
224                 scope = LDAP_SCOPE_SUBTREE;
225                 } else {
226                 fprintf( stderr, "scope should be base, one, or sub\n" );
227                 usage( argv[ 0 ] );
228                 }
229                 break;
230
231         case 'a':       /* set alias deref option */
232                 if ( strcasecmp( optarg, "never" ) == 0 ) {
233                 deref = LDAP_DEREF_NEVER;
234                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
235                 deref = LDAP_DEREF_SEARCHING;
236                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
237                 deref = LDAP_DEREF_FINDING;
238                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
239                 deref = LDAP_DEREF_ALWAYS;
240                 } else {
241                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
242                 usage( argv[ 0 ] );
243                 }
244                 break;
245                 
246         case 'T':       /* field separator */
247                 if( tmpdir ) free( tmpdir );
248                 tmpdir = strdup( optarg );
249                 break;
250         case 'V':       /* field separator */
251                 if( urlpre ) free( urlpre );
252                 urlpre = strdup( optarg );
253                 break;
254         case 'f':       /* input file */
255                 infile = strdup( optarg );
256                 break;
257         case 'h':       /* ldap host */
258                 ldaphost = strdup( optarg );
259                 break;
260         case 'b':       /* searchbase */
261                 base = strdup( optarg );
262                 break;
263         case 'D':       /* bind DN */
264                 binddn = strdup( optarg );
265                 break;
266         case 'p':       /* ldap port */
267                 ldapport = atoi( optarg );
268                 break;
269         case 'w':       /* bind password */
270                 passwd.bv_val = strdup( optarg );
271                 {
272                         char* p;
273
274                         for( p = optarg; *p == '\0'; p++ ) {
275                                 *p = '*';
276                         }
277                 }
278                 passwd.bv_len = strlen( passwd.bv_val );
279                 break;
280         case 'l':       /* time limit */
281                 timelimit = atoi( optarg );
282                 break;
283         case 'z':       /* size limit */
284                 sizelimit = atoi( optarg );
285                 break;
286         case 'S':       /* sort attribute */
287                 sortattr = strdup( optarg );
288                 break;
289         case 'W':
290                 want_bindpw++;
291                 break;
292         case 'P':
293                 switch( atoi( optarg ) )
294                 {
295                 case 2:
296                         version = LDAP_VERSION2;
297                         break;
298                 case 3:
299                         version = LDAP_VERSION3;
300                         break;
301                 default:
302                         fprintf( stderr, "protocol version should be 2 or 3\n" );
303                         usage( argv[0] );
304                 }
305                 break;
306         case 'I':
307 #ifdef HAVE_CYRUS_SASL
308                 sasl_integrity++;
309                 authmethod = LDAP_AUTH_SASL;
310 #else
311                 fprintf( stderr, "%s was not compiled with SASL support\n",
312                         argv[0] );
313                 return( EXIT_FAILURE );
314 #endif
315                 break;
316         case 'E':
317 #ifdef HAVE_CYRUS_SASL
318                 sasl_privacy++;
319                 authmethod = LDAP_AUTH_SASL;
320 #else
321                 fprintf( stderr, "%s was not compiled with SASL support\n",
322                         argv[0] );
323                 return( EXIT_FAILURE );
324 #endif
325                 break;
326         case 'Y':
327 #ifdef HAVE_CYRUS_SASL
328                 if ( strcasecmp( optarg, "any" ) && strcmp( optarg, "*" ) ) {
329                         sasl_mech = strdup( optarg );
330                 }
331                 authmethod = LDAP_AUTH_SASL;
332 #else
333                 fprintf( stderr, "%s was not compiled with SASL support\n",
334                         argv[0] );
335                 return( EXIT_FAILURE );
336 #endif
337                 break;
338         case 'U':
339 #ifdef HAVE_CYRUS_SASL
340                 sasl_authc_id = strdup( optarg );
341                 authmethod = LDAP_AUTH_SASL;
342 #else
343                 fprintf( stderr, "%s was not compiled with SASL support\n",
344                         argv[0] );
345                 return( EXIT_FAILURE );
346 #endif
347                 break;
348         case 'X':
349 #ifdef HAVE_CYRUS_SASL
350                 sasl_authz_id = strdup( optarg );
351                 authmethod = LDAP_AUTH_SASL;
352 #else
353                 fprintf( stderr, "%s was not compiled with SASL support\n",
354                         argv[0] );
355                 return( EXIT_FAILURE );
356 #endif
357                 break;
358         case 'Z':
359 #ifdef HAVE_TLS
360                 use_tls++;
361 #else
362                 fprintf( stderr, "%s was not compiled with TLS support\n",
363                         argv[0] );
364                 return( EXIT_FAILURE );
365 #endif
366                 break;
367         default:
368                 usage( argv[0] );
369         }
370         }
371
372         /* no alternative format */
373         if( ldif == 0 ) ldif = 1;
374
375         if ( ( authmethod == LDAP_AUTH_KRBV4 ) || ( authmethod ==
376                         LDAP_AUTH_KRBV41 ) ) {
377                 if( version > LDAP_VERSION2 ) {
378                         fprintf( stderr, "Kerberos requires LDAPv2\n" );
379                         return( EXIT_FAILURE );
380                 }
381                 version = LDAP_VERSION2;
382         }
383         else if ( authmethod == LDAP_AUTH_SASL ) {
384                 if( version != -1 && version != LDAP_VERSION3 ) {
385                         fprintf( stderr, "SASL requires LDAPv3\n" );
386                         return( EXIT_FAILURE );
387                 }
388                 version = LDAP_VERSION3;
389         }
390
391         if( manageDSAit ) {
392                 if( version != -1 && version != LDAP_VERSION3 ) {
393                         fprintf(stderr, "manage DSA control requires LDAPv3\n");
394                         return EXIT_FAILURE;
395                 }
396                 version = LDAP_VERSION3;
397         }
398
399         if( use_tls ) {
400                 if( version != -1 && version != LDAP_VERSION3 ) {
401                         fprintf(stderr, "Start TLS requires LDAPv3\n");
402                         return EXIT_FAILURE;
403                 }
404                 version = LDAP_VERSION3;
405         }
406
407         if ( argc - optind < 1 ) {
408                 usage( argv[ 0 ] );
409         }
410
411         filtpattern = strdup( argv[ optind ] );
412
413         if ( argv[ optind + 1 ] == NULL ) {
414                 attrs = NULL;
415         } else if ( sortattr == NULL || *sortattr == '\0' ) {
416                 attrs = &argv[ optind + 1 ];
417         } else {
418                 for ( i = optind + 1; i < argc; i++ ) {
419                         if ( strcasecmp( argv[ i ], sortattr ) == 0 ) {
420                                 break;
421                         }
422                 }
423                 if ( i == argc ) {
424                         skipsortattr = 1;
425                         argv[ optind ] = sortattr;
426                 } else {
427                         optind++;
428                 }
429                 attrs = &argv[ optind ];
430         }
431
432         if ( infile != NULL ) {
433                 if ( infile[0] == '-' && infile[1] == '\0' ) {
434                         fp = stdin;
435                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
436                         perror( infile );
437                         return EXIT_FAILURE;
438                 }
439         }
440
441         if( tmpdir == NULL
442                 && (tmpdir = getenv("TMPDIR")) == NULL
443                 && (tmpdir = getenv("TMP")) == NULL
444                 && (tmpdir = getenv("TEMP")) == NULL )
445         {
446                 tmpdir = "/tmp";
447         }
448
449         if( urlpre == NULL ) {
450                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
451
452                 if( urlpre == NULL ) {
453                         perror( "malloc" );
454                         return EXIT_FAILURE;
455                 }
456
457                 sprintf( urlpre, "file:///%s/",
458                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
459
460                 /* urlpre should be URLized.... */
461         }
462
463         if ( debug ) {
464                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
465                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
466                 }
467                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
468                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
469                 }
470                 ldif_debug = debug;
471         }
472
473 #ifdef SIGPIPE
474         (void) SIGNAL( SIGPIPE, SIG_IGN );
475 #endif
476
477         if ( verbose ) {
478                 fprintf( stderr,
479                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
480                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
481                         ldapport );
482         }
483
484         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
485                 perror( "ldap_init" );
486                 return( EXIT_FAILURE );
487         }
488
489         if (deref != -1 &&
490                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
491         {
492                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
493         }
494         if (timelimit != -1 &&
495                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
496         {
497                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
498         }
499         if (sizelimit != -1 &&
500                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
501         {
502                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
503         }
504         if (referrals != -1 &&
505                 ldap_set_option( ld, LDAP_OPT_REFERRALS,
506                                  (referrals ? LDAP_OPT_ON : LDAP_OPT_OFF) ) != LDAP_OPT_SUCCESS )
507         {
508                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
509                         referrals ? "on" : "off" );
510         }
511
512         if (version == -1 ) {
513                 version = 3;
514         }
515
516         if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
517                 != LDAP_OPT_SUCCESS )
518         {
519                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
520                         version );
521         }
522
523         if ( use_tls && ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
524                 if ( use_tls > 1 ) {
525                         ldap_perror( ld, "ldap_start_tls" );
526                         return( EXIT_FAILURE );
527                 }
528         }
529
530         if (want_bindpw) {
531                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
532                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
533         }
534
535         if ( authmethod == LDAP_AUTH_SASL ) {
536 #ifdef HAVE_CYRUS_SASL
537                 int     minssf = 0, maxssf = 0;
538
539                 if ( sasl_integrity > 0 )
540                         maxssf = 1;
541                 if ( sasl_integrity > 1 )
542                         minssf = 1;
543                 if ( sasl_privacy > 0 )
544                         maxssf = 100000; /* Something big value */
545                 if ( sasl_privacy > 1 )
546                         minssf = 56;
547                 
548                 if ( ldap_set_option( ld, LDAP_OPT_X_SASL_MINSSF,
549                                 (void *)&minssf ) != LDAP_OPT_SUCCESS ) {
550                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_MINSSF"
551                                 "%d\n", minssf);
552                         return( EXIT_FAILURE );
553                 }
554                 if ( ldap_set_option( ld, LDAP_OPT_X_SASL_MAXSSF,
555                                 (void *)&maxssf ) != LDAP_OPT_SUCCESS ) {
556                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_MAXSSF"
557                                 "%d\n", maxssf);
558                         return( EXIT_FAILURE );
559                 }
560                 
561                 rc = ldap_negotiated_sasl_bind_s( ld, binddn, sasl_authc_id,
562                                 sasl_authz_id, sasl_mech,
563                                 passwd.bv_len ? &passwd : NULL,
564                                 NULL, NULL );
565
566                 if( rc != LDAP_SUCCESS ) {
567                         ldap_perror( ld, "ldap_negotiated_sasl_bind_s" );
568                         return( EXIT_FAILURE );
569                 }
570 #else
571                 fprintf( stderr, "%s was not compiled with SASL support\n",
572                         argv[0] );
573                 return( EXIT_FAILURE );
574 #endif
575         } else {
576                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
577                                 != LDAP_SUCCESS ) {
578                         ldap_perror( ld, "ldap_bind" );
579                         return( EXIT_FAILURE );
580                 }
581         }
582
583         if ( manageDSAit ) {
584                 int err;
585                 LDAPControl c;
586                 LDAPControl *ctrls[2];
587                 ctrls[0] = &c;
588                 ctrls[1] = NULL;
589
590                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
591                 c.ldctl_value.bv_val = NULL;
592                 c.ldctl_value.bv_len = 0;
593                 c.ldctl_iscritical = manageDSAit > 1;
594
595                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
596
597                 if( err != LDAP_OPT_SUCCESS ) {
598                         fprintf( stderr, "Could not set Manage DSA IT Control\n" );
599                         if( c.ldctl_iscritical ) {
600                                 exit( EXIT_FAILURE );
601                         }
602                 }
603         }
604
605         if ( verbose ) {
606                 fprintf( stderr, "filter%s: %s\nreturning: ",
607                         infile != NULL ? " pattern" : "",
608                         filtpattern );
609
610                 if ( attrs == NULL ) {
611                         fprintf( stderr, "ALL" );
612                 } else {
613                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
614                                 fprintf( stderr, "%s ", attrs[ i ] );
615                         }
616                 }
617                 fprintf( stderr, "\n" );
618         }
619
620         if (ldif < 3 ) {
621                 printf( "version: 2\n\n");
622         }
623
624         if (ldif < 2 ) {
625                 printf( "#\n# filter%s: %s\n# returning: ",
626                         infile != NULL ? " pattern" : "",
627                         filtpattern );
628
629                 if ( attrs == NULL ) {
630                         printf( "ALL" );
631                 } else {
632                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
633                                 printf( "%s ", attrs[ i ] );
634                         }
635                 }
636                 printf( "\n#\n\n" );
637         }
638
639         if ( infile == NULL ) {
640                 rc = dosearch( ld, base, scope, attrs, attrsonly, NULL, filtpattern );
641
642         } else {
643                 rc = 0;
644                 first = 1;
645                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
646                         line[ strlen( line ) - 1 ] = '\0';
647                         if ( !first ) {
648                                 putchar( '\n' );
649                         } else {
650                                 first = 0;
651                         }
652                         rc = dosearch( ld, base, scope, attrs, attrsonly,
653                                 filtpattern, line );
654                 }
655                 if ( fp != stdin ) {
656                         fclose( fp );
657                 }
658         }
659
660         ldap_unbind( ld );
661         return( rc );
662 }
663
664
665 static int dosearch(
666         LDAP    *ld,
667         char    *base,
668         int             scope,
669         char    **attrs,
670         int             attrsonly,
671         char    *filtpatt,
672         char    *value)
673 {
674         char            filter[ BUFSIZ ];
675         int                     rc, first;
676         int                     nresponses;
677         int                     nentries;
678         int                     nreferences;
679         int                     nextended;
680         int                     npartial;
681         LDAPMessage             *res, *msg;
682         ber_int_t       msgid;
683
684         if( filtpatt != NULL ) {
685                 sprintf( filter, filtpatt, value );
686
687                 if ( verbose ) {
688                         fprintf( stderr, "filter is: (%s)\n", filter );
689                 }
690
691                 if( ldif == 1 ) {
692                         printf( "#\n# filter: %s\n#\n", filter );
693                 }
694
695         } else {
696                 sprintf( filter, "%s", value );
697         }
698
699         if ( not ) {
700                 return( LDAP_SUCCESS );
701         }
702
703         msgid = ldap_search( ld, base, scope, filter, attrs, attrsonly );
704         if( msgid == -1 ) {
705                 int ld_errno;
706                 ldap_perror( ld, "ldap_search" );
707                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ld_errno);
708                 return( ld_errno );
709         }
710
711         nresponses = nentries = nreferences = nextended = npartial = 0;
712
713         res = NULL;
714         while ((rc = ldap_result( ld, LDAP_RES_ANY,
715                 sortattr ? 1 : 0, NULL, &res )) > 0 )
716         {
717                 if( sortattr ) {
718                         (void) ldap_sort_entries( ld, &res,
719                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
720                 }
721
722                 for ( msg = ldap_first_message( ld, res );
723                         msg != NULL;
724                         msg = ldap_next_message( ld, msg ) )
725                 {
726                         nresponses++;
727
728                         switch( ldap_msgtype( msg ) ) {
729                         case LDAP_RES_SEARCH_ENTRY:
730                                 if( nresponses > 1 ) putchar('\n');
731                                 nentries++;
732                                 print_entry( ld, msg, attrsonly );
733                                 break;
734
735                         case LDAP_RES_SEARCH_REFERENCE:
736                                 if( nresponses > 1 ) putchar('\n');
737                                 nreferences++;
738                                 print_reference( ld, msg );
739                                 break;
740
741                         case LDAP_RES_EXTENDED:
742                                 if( nresponses > 1 ) putchar('\n');
743                                 nextended++;
744                                 print_extended( ld, msg );
745
746                                 rc = ldap_result2error( ld, msg, 0 );
747
748                                 if( rc != LDAP_SUCCESS ) {
749                                         ldap_perror( ld, "ldap_search" );
750                                 }
751
752                                 if( ldap_msgid( msg ) == 0 ) {
753                                         /* unsolicited extended operation */
754                                         goto done;
755                                 }
756
757                                 break;
758
759                         case LDAP_RES_EXTENDED_PARTIAL:
760                                 if( nresponses > 1 ) putchar('\n');
761                                 npartial++;
762                                 print_partial( ld, msg );
763                                 break;
764
765                         case LDAP_RES_SEARCH_RESULT:
766                                 /* if( nresponses > 1 ) putchar('\n'); */
767                                 rc = ldap_result2error( ld, msg, 0 );
768
769                                 if( rc != LDAP_SUCCESS ) {
770                                         ldap_perror( ld, "ldap_search" );
771                                 }
772
773                                 goto done;
774
775                         }
776                 }
777
778                 ldap_msgfree( res );
779         }
780
781         if ( rc == -1 ) {
782                 ldap_perror( ld, "ldap_result" );
783                 return( rc );
784         }
785
786 done:
787         if ( verbose ) {
788                 printf( "%d responses\n", nresponses );
789         }
790
791         return( rc );
792 }
793
794
795 static void print_reference(
796         LDAP *ld,
797         LDAPMessage *reference )
798 {
799         int rc, i;
800         char **refs = NULL;
801
802         if( ldif == 1 ) {
803                 printf("# search reference\n");
804         }
805
806         rc = ldap_parse_reference( ld, reference, &refs, NULL, 0 );
807
808         for( i=0; refs[i] != NULL; i++ ) {
809                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
810         }
811
812         ber_memvfree( (void **) refs );
813
814         if( rc != LDAP_SUCCESS ) {
815                 ldap_perror(ld, "ldap_parse_reference");
816                 exit( EXIT_FAILURE );
817         }
818 }
819
820 static void print_extended(
821         LDAP *ld,
822         LDAPMessage *extended )
823 {
824         char rst[16];
825         int rc;
826         char *retoid = NULL;
827         struct berval *retdata = NULL;
828
829         if( ldif == 1 ) {
830                 printf("# extended result response\n");
831         }
832
833         rc = ldap_parse_extended_result( ld, extended,
834                 &retoid, &retdata, 0 );
835
836         write_ldif( LDIF_PUT_VALUE, "extended",
837                 retoid, retoid ? strlen(retoid) : 0 );
838
839         if(retdata) {
840                 write_ldif( LDIF_PUT_BINARY, "data", 
841                         retdata->bv_val, retdata->bv_len );
842         }
843
844         sprintf( rst, "%ld", (long) rst );
845         write_ldif( LDIF_PUT_VALUE, "result", rst, strlen(rst));
846
847         if( rc != LDAP_SUCCESS ) {
848                 ldap_perror(ld, "ldap_parse_extended_result");
849                 exit( EXIT_FAILURE );
850         }
851 }
852
853 static void print_partial(
854         LDAP *ld,
855         LDAPMessage *partial )
856 {
857         int rc;
858         char *retoid = NULL;
859         struct berval *retdata = NULL;
860
861         if( ldif == 1 ) {
862                 printf("# extended partial response\n");
863         }
864
865         rc = ldap_parse_extended_partial( ld, partial,
866                 &retoid, &retdata, NULL, 0 );
867
868         write_ldif( LDIF_PUT_VALUE, "partial",
869                 retoid, retoid ? strlen(retoid) : 0 );
870
871         if(retdata) {
872                 write_ldif( LDIF_PUT_BINARY, "data", 
873                         retdata->bv_val, retdata->bv_len );
874         }
875
876         if( rc != LDAP_SUCCESS ) {
877                 ldap_perror(ld, "ldap_parse_extended_partial");
878                 exit( EXIT_FAILURE );
879         }
880 }
881
882 static void
883 print_entry(
884         LDAP    *ld,
885         LDAPMessage     *entry,
886         int             attrsonly)
887 {
888         char            *a, *dn, *ufn;
889         char    tmpfname[ 256 ];
890         char    url[ 256 ];
891         int                     i;
892         BerElement              *ber = NULL;
893         struct berval   **bvals;
894         FILE            *tmpfp;
895
896         dn = ldap_get_dn( ld, entry );
897         ufn = NULL;
898
899         if ( ldif == 1 ) {
900                 ufn = ldap_dn2ufn( dn );
901                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
902         }
903         if ( ldif ) {
904                 write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
905         } else {
906                 printf( "%s\n", dn );
907         }
908
909         if ( includeufn ) {
910                 if( ufn == NULL ) {
911                         ufn = ldap_dn2ufn( dn );
912                 }
913                 if ( ldif ) {
914                         write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
915                 } else {
916                         printf( "%s\n", ufn );
917                 }
918         }
919
920         if( ufn != NULL ) ldap_memfree( ufn );
921         ldap_memfree( dn );
922
923         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
924                 a = ldap_next_attribute( ld, entry, ber ) )
925         {
926                 if ( skipsortattr && strcasecmp( a, sortattr ) == 0 ) {
927                         continue;
928                 }
929
930                 if ( attrsonly ) {
931                         if ( ldif ) {
932                                 write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
933                         } else {
934                                 printf( "%s\n", a );
935                         }
936
937                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
938                         for ( i = 0; bvals[i] != NULL; i++ ) {
939                                 if ( vals2tmp > 1 || ( vals2tmp
940                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
941                                 {
942                                         int tmpfd;
943                                         /* write value to file */
944                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
945                                                 tmpdir, a );
946                                         tmpfp = NULL;
947
948                                         if ( mktemp( tmpfname ) == NULL ) {
949                                                 perror( tmpfname );
950                                                 continue;
951                                         }
952
953                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
954                                                 perror( tmpfname );
955                                                 continue;
956                                         }
957
958                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
959                                                 perror( tmpfname );
960                                                 continue;
961                                         }
962
963                                         if ( fwrite( bvals[ i ]->bv_val,
964                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
965                                         {
966                                                 perror( tmpfname );
967                                                 fclose( tmpfp );
968                                                 continue;
969                                         }
970
971                                         fclose( tmpfp );
972
973                                         sprintf( url, "%s%s", urlpre,
974                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
975
976                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
977
978                                 } else {
979                                         write_ldif( LDIF_PUT_VALUE, a,
980                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
981                                 }
982                         }
983                         ber_bvecfree( bvals );
984                 }
985         }
986
987         if( ber != NULL ) {
988                 ber_free( ber, 0 );
989         }
990 }
991
992
993 static int
994 write_ldif( int type, char *name, char *value, ber_len_t vallen )
995 {
996         char    *ldif;
997
998         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
999                 return( -1 );
1000         }
1001
1002         fputs( ldif, stdout );
1003         ber_memfree( ldif );
1004
1005         return( 0 );
1006 }