]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
0bae49a3e1530c3f27b31e876f286ab0582a2781
[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 #undef DEPSEP
36 #define DEFSEP          "="
37
38 static void
39 usage( const char *s )
40 {
41         fprintf( stderr,
42 "usage: %s [options] filter [attributes...]\nwhere:\n"
43 "       filter\tRFC-1558 compliant LDAP search filter\n"
44 "       attributes\twhitespace-separated list of attributes to retrieve\n"
45 "\t\t1.1                -- no attributes\n"
46 "\t\t*            -- all user attributes\n"
47 "\t\t+            -- all operational attributes\n"
48 "\t\tempty list -- all non-operational attributes\n"
49 "options:\n"
50 "       -a deref\tone of `never', `always', `search', or `find' (alias\n"
51 "               \tdereferencing)\n"
52 "       -A\t\tretrieve attribute names only (no values)\n"
53 "       -b basedn\tbase dn for search\n"
54 "       -B\t\tdo not suppress printing of binary values\n"
55 "       -d level\tset LDAP debugging level to `level'\n"
56 "       -D binddn\tbind DN\n"
57 "       -E\t\trequest SASL privacy (-EE to make it critical)\n"
58 "       -f file\t\tperform sequence of searches listed in `file'\n"
59 "       -F sep\t\tprint `sep' instead of `=' between attribute names and\n"
60 "               \tvalues\n"
61 "       -h host\t\tLDAP server\n"
62 "       -I\t\trequest SASL integrity checking (-II to make it\n"
63 "               \tcritical)\n"
64 "       -k\t\tuse Kerberos authentication\n"
65 "       -K\t\tlike -k, but do only step 1 of the Kerberos bind\n"
66 "       -l limit\ttime limit (in seconds) for search\n"
67 "       -L\t\tprint entries in LDIF format (implies -B)\n"
68 "       -LL\t\tprint entries in LDIF format without comments\n"
69 "       -LLL\t\tprint entries in LDIF format without comments and\n"
70 "               \tversion\n"
71 "       -M\t\tenable Manage DSA IT control (-MM to make critical)\n"
72 "       -n\t\tshow what would be done but don't actually search\n"
73 "       -p port\t\tport on LDAP server\n"
74 "       -P version\tprocotol version (2 or 3)\n"
75 "       -R\t\tdo not automatically follow referrals\n"
76 "       -s scope\tone of base, one, or sub (search scope)\n"
77 "       -S attr\t\tsort the results by attribute `attr'\n"
78 "       -t\t\twrite binary values to files in TMPDIR\n"
79 "       -tt\t\twrite all values to files in TMPDIR\n"
80 "       -T path\t\twrite files to directory specified by path (default:\n"
81 "               \t\"/tmp\")\n"
82 "       -u\t\tinclude User Friendly entry names in the output\n"
83 "       -U user\t\tSASL authentication identity (username)\n"
84 "       -v\t\trun in verbose mode (diagnostics to standard output)\n"
85 "       -V prefix\tURL prefix for files (default: \"file://tmp/\")\n"
86 "       -w passwd\tbind passwd (for simple authentication)\n"
87 "       -W\t\tprompt for bind passwd\n"
88 "       -X id\t\tSASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
89 "       -Y mech\t\tSASL mechanism\n"
90 "       -z limit\tsize limit (in entries) for search\n"
91 "       -Z\t\trequest the use of TLS (-ZZ to make it critical)\n"
92 ,               s );
93
94         exit( EXIT_FAILURE );
95 }
96
97 static void print_entry LDAP_P((
98         LDAP    *ld,
99         LDAPMessage     *entry,
100         int             attrsonly));
101
102 static int write_ldif LDAP_P((
103         int type,
104         char *name,
105         char *value,
106         ber_len_t vallen ));
107
108 static int dosearch LDAP_P((
109         LDAP    *ld,
110         char    *base,
111         int             scope,
112         char    **attrs,
113         int             attrsonly,
114         char    *filtpatt,
115         char    *value));
116
117 #define TMPDIR "/tmp"
118 #define URLPRE "file:/tmp/"
119
120 static char *tmpdir = NULL;
121 static char *urlpre = NULL;
122
123 static char     *binddn = NULL;
124 static struct berval passwd = { 0, NULL };
125 static char     *base = NULL;
126 static char     *ldaphost = NULL;
127 static int      ldapport = 0;
128 #ifdef HAVE_CYRUS_SASL
129 static char     *sasl_authc_id = NULL;
130 static char     *sasl_authz_id = NULL;
131 static char     *sasl_mech = NULL;
132 static int      sasl_integrity = 0;
133 static int      sasl_privacy = 0;
134 #endif
135 static int      use_tls = 0;
136 static char     *sep = DEFSEP;
137 static char     *sortattr = NULL;
138 static int      skipsortattr = 0;
139 static int      verbose, not, includeufn, binary, vals2tmp, ldif;
140
141 int
142 main( int argc, char **argv )
143 {
144         char            *infile, *filtpattern, **attrs, line[ BUFSIZ ];
145         FILE            *fp = NULL;
146         int                     rc, i, first, scope, deref, attrsonly, manageDSAit;
147         int                     referrals, timelimit, sizelimit, debug;
148         int             authmethod, version, want_bindpw;
149         LDAP            *ld;
150
151         infile = NULL;
152         debug = verbose = binary = not = vals2tmp =
153                 attrsonly = manageDSAit = ldif = want_bindpw = 0;
154
155         deref = sizelimit = timelimit = version = -1;
156
157         /* default should be off */
158         referrals = 1;
159
160         scope = LDAP_SCOPE_SUBTREE;
161         authmethod = LDAP_AUTH_SIMPLE;
162
163         while (( i = getopt( argc, argv,
164                 "Aa:Bb:D:d:EF:f:h:IKkLl:MnP:p:RS:s:T:tU:uV:vWw:X:Y:Zz:")) != EOF )
165         {
166         switch( i ) {
167         case 'n':       /* do Not do any searches */
168                 ++not;
169                 break;
170         case 'v':       /* verbose mode */
171                 ++verbose;
172                 break;
173         case 'd':
174                 debug |= atoi( optarg );
175                 break;
176         case 'k':       /* use kerberos bind */
177 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
178                 authmethod = LDAP_AUTH_KRBV4;
179 #else
180                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
181                 return( EXIT_FAILURE );
182 #endif
183                 break;
184         case 'K':       /* use kerberos bind, 1st part only */
185 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
186                 authmethod = LDAP_AUTH_KRBV41;
187 #else
188                 fprintf( stderr, "%s was not compiled with Kerberos support\n", argv[0] );
189                 return( EXIT_FAILURE );
190 #endif
191                 break;
192                 break;
193         case 'u':       /* include UFN */
194                 ++includeufn;
195                 break;
196         case 't':       /* write attribute values to /tmp files */
197                 ++vals2tmp;
198                 break;
199         case 'M':
200                 /* enable Manage DSA IT */
201                 manageDSAit++;
202                 break;
203         case 'R':       /* don't automatically chase referrals */
204                 referrals = 0;
205                 break;
206         case 'A':       /* retrieve attribute names only -- no values */
207                 ++attrsonly;
208                 break;
209         case 'L':       /* print entries in LDIF format */
210                 ++ldif;
211                 /* fall through -- always allow binary when outputting LDIF */
212         case 'B':       /* allow binary values to be printed */
213                 ++binary;
214                 break;
215         case 's':       /* search scope */
216                 if ( strcasecmp( optarg, "base" ) == 0 ) {
217                 scope = LDAP_SCOPE_BASE;
218                 } else if ( strcasecmp( optarg, "one" ) == 0 ) {
219                 scope = LDAP_SCOPE_ONELEVEL;
220                 } else if ( strcasecmp( optarg, "sub" ) == 0 ) {
221                 scope = LDAP_SCOPE_SUBTREE;
222                 } else {
223                 fprintf( stderr, "scope should be base, one, or sub\n" );
224                 usage( argv[ 0 ] );
225                 }
226                 break;
227
228         case 'a':       /* set alias deref option */
229                 if ( strcasecmp( optarg, "never" ) == 0 ) {
230                 deref = LDAP_DEREF_NEVER;
231                 } else if ( strcasecmp( optarg, "search" ) == 0 ) {
232                 deref = LDAP_DEREF_SEARCHING;
233                 } else if ( strcasecmp( optarg, "find" ) == 0 ) {
234                 deref = LDAP_DEREF_FINDING;
235                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
236                 deref = LDAP_DEREF_ALWAYS;
237                 } else {
238                 fprintf( stderr, "alias deref should be never, search, find, or always\n" );
239                 usage( argv[ 0 ] );
240                 }
241                 break;
242                 
243         case 'T':       /* field separator */
244                 if( tmpdir ) free( tmpdir );
245                 tmpdir = strdup( optarg );
246                 break;
247         case 'V':       /* field separator */
248                 if( urlpre ) free( urlpre );
249                 urlpre = strdup( optarg );
250                 break;
251         case 'F':       /* field separator */
252                 sep = 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 #ifdef LDAP_LDIF
373         /* no alternative format */
374         if( ldif < 1 ) ldif = 1;
375 #endif
376
377         if ( ( authmethod == LDAP_AUTH_KRBV4 ) || ( authmethod ==
378                         LDAP_AUTH_KRBV41 ) ) {
379                 if( version > LDAP_VERSION2 ) {
380                         fprintf( stderr, "Kerberos requires LDAPv2\n" );
381                         return( EXIT_FAILURE );
382                 }
383                 version = LDAP_VERSION2;
384         }
385         else if ( authmethod == LDAP_AUTH_SASL ) {
386                 if( version != -1 && version != LDAP_VERSION3 ) {
387                         fprintf( stderr, "SASL requires LDAPv3\n" );
388                         return( EXIT_FAILURE );
389                 }
390                 version = LDAP_VERSION3;
391         }
392
393         if( manageDSAit ) {
394                 if( version != -1 && version != LDAP_VERSION3 ) {
395                         fprintf(stderr, "manage DSA control requires LDAPv3\n");
396                         return EXIT_FAILURE;
397                 }
398                 version = LDAP_VERSION3;
399         }
400
401         if( use_tls ) {
402                 if( version != -1 && version != LDAP_VERSION3 ) {
403                         fprintf(stderr, "Start TLS requires LDAPv3\n");
404                         return EXIT_FAILURE;
405                 }
406                 version = LDAP_VERSION3;
407         }
408
409         if ( argc - optind < 1 ) {
410                 usage( argv[ 0 ] );
411         }
412
413         filtpattern = strdup( argv[ optind ] );
414
415         if ( argv[ optind + 1 ] == NULL ) {
416                 attrs = NULL;
417         } else if ( sortattr == NULL || *sortattr == '\0' ) {
418                 attrs = &argv[ optind + 1 ];
419         } else {
420                 for ( i = optind + 1; i < argc; i++ ) {
421                         if ( strcasecmp( argv[ i ], sortattr ) == 0 ) {
422                                 break;
423                         }
424                 }
425                 if ( i == argc ) {
426                         skipsortattr = 1;
427                         argv[ optind ] = sortattr;
428                 } else {
429                         optind++;
430                 }
431                 attrs = &argv[ optind ];
432         }
433
434         if ( infile != NULL ) {
435                 if ( infile[0] == '-' && infile[1] == '\0' ) {
436                         fp = stdin;
437                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
438                         perror( infile );
439                         return EXIT_FAILURE;
440                 }
441         }
442
443         if( tmpdir == NULL
444                 && (tmpdir = getenv("TMPDIR")) == NULL
445                 && (tmpdir = getenv("TMP")) == NULL
446                 && (tmpdir = getenv("TEMP")) == NULL )
447         {
448                 tmpdir = "/tmp";
449         }
450
451         if( urlpre == NULL ) {
452                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
453
454                 if( urlpre == NULL ) {
455                         perror( "malloc" );
456                         return EXIT_FAILURE;
457                 }
458
459                 sprintf( urlpre, "file:///%s/",
460                         tmpdir[0] == '/' ? &tmpdir[1] : tmpdir );
461
462                 /* urlpre should be URLized.... */
463         }
464
465         if ( debug ) {
466                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
467                         fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
468                 }
469                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
470                         fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
471                 }
472                 ldif_debug = debug;
473         }
474
475 #ifdef SIGPIPE
476         (void) SIGNAL( SIGPIPE, SIG_IGN );
477 #endif
478
479         if ( verbose ) {
480                 fprintf( stderr,
481                         (ldapport ? "ldap_init( %s, %d )\n" : "ldap_init( %s, <DEFAULT> )\n"),
482                         (ldaphost != NULL) ? ldaphost : "<DEFAULT>",
483                         ldapport );
484         }
485
486         if (( ld = ldap_init( ldaphost, ldapport )) == NULL ) {
487                 perror( "ldap_init" );
488                 return( EXIT_FAILURE );
489         }
490
491         if (deref != -1 &&
492                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
493         {
494                 fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
495         }
496         if (timelimit != -1 &&
497                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
498         {
499                 fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
500         }
501         if (sizelimit != -1 &&
502                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
503         {
504                 fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
505         }
506         if (referrals != -1 &&
507                 ldap_set_option( ld, LDAP_OPT_REFERRALS,
508                                  (referrals ? LDAP_OPT_ON : LDAP_OPT_OFF) ) != LDAP_OPT_SUCCESS )
509         {
510                 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
511                         referrals ? "on" : "off" );
512         }
513
514         if (version != -1 &&
515                 ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version ) != LDAP_OPT_SUCCESS )
516         {
517                 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", version );
518         }
519
520         if ( use_tls && ldap_start_tls( ld, NULL, NULL ) != LDAP_SUCCESS ) {
521                 if ( use_tls > 1 ) {
522                         ldap_perror( ld, "ldap_start_tls" );
523                         return( EXIT_FAILURE );
524                 }
525         }
526
527         if (want_bindpw) {
528                 passwd.bv_val = getpassphrase("Enter LDAP Password: ");
529                 passwd.bv_len = strlen( passwd.bv_val );
530         }
531
532         if ( authmethod == LDAP_AUTH_SASL ) {
533 #ifdef HAVE_CYRUS_SASL
534                 int     minssf = 0, maxssf = 0;
535
536                 if ( sasl_integrity > 0 )
537                         maxssf = 1;
538                 if ( sasl_integrity > 1 )
539                         minssf = 1;
540                 if ( sasl_privacy > 0 )
541                         maxssf = 100000; /* Something big value */
542                 if ( sasl_privacy > 1 )
543                         minssf = 56;
544                 
545                 if ( ldap_set_option( ld, LDAP_OPT_X_SASL_MINSSF,
546                                 (void *)&minssf ) != LDAP_OPT_SUCCESS ) {
547                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_MINSSF"
548                                 "%d\n", minssf);
549                         return( EXIT_FAILURE );
550                 }
551                 if ( ldap_set_option( ld, LDAP_OPT_X_SASL_MAXSSF,
552                                 (void *)&maxssf ) != LDAP_OPT_SUCCESS ) {
553                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_MAXSSF"
554                                 "%d\n", maxssf);
555                         return( EXIT_FAILURE );
556                 }
557                 
558                 rc = ldap_negotiated_sasl_bind_s( ld, binddn, sasl_authc_id,
559                                 sasl_authz_id, sasl_mech,
560                                 passwd.bv_len ? &passwd : NULL,
561                                 NULL, NULL );
562
563                 if( rc != LDAP_SUCCESS ) {
564                         ldap_perror( ld, "ldap_negotiated_sasl_bind_s" );
565                         return( EXIT_FAILURE );
566                 }
567 #else
568                 fprintf( stderr, "%s was not compiled with SASL support\n",
569                         argv[0] );
570                 return( EXIT_FAILURE );
571 #endif
572         }
573         else {
574                 if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
575                                 != LDAP_SUCCESS ) {
576                         ldap_perror( ld, "ldap_bind" );
577                         return( EXIT_FAILURE );
578                 }
579         }
580
581         if ( manageDSAit ) {
582                 int err;
583                 LDAPControl c;
584                 LDAPControl *ctrls[2];
585                 ctrls[0] = &c;
586                 ctrls[1] = NULL;
587
588                 c.ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
589                 c.ldctl_value.bv_val = NULL;
590                 c.ldctl_value.bv_len = 0;
591                 c.ldctl_iscritical = manageDSAit > 1;
592
593                 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, &ctrls );
594
595                 if( err != LDAP_OPT_SUCCESS ) {
596                         fprintf( stderr, "Could not set Manage DSA IT Control\n" );
597                         if( c.ldctl_iscritical ) {
598                                 exit( EXIT_FAILURE );
599                         }
600                 }
601         }
602
603         if ( verbose ) {
604                 fprintf( stderr, "filter%s: %s\nreturning: ",
605                         infile != NULL ? " pattern" : "",
606                         filtpattern );
607
608                 if ( attrs == NULL ) {
609                         fprintf( stderr, "ALL" );
610                 } else {
611                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
612                                 fprintf( stderr, "%s ", attrs[ i ] );
613                         }
614                 }
615                 fprintf( stderr, "\n" );
616         }
617
618         if ( ldif ) {
619                 if (ldif < 3 ) {
620                         printf( "version: 1\n\n");
621                 }
622
623                 if (ldif < 2 ) {
624                         printf( "#\n# filter%s: %s\n# returning: ",
625                                 infile != NULL ? " pattern" : "",
626                                 filtpattern );
627
628                         if ( attrs == NULL ) {
629                                 printf( "ALL" );
630                         } else {
631                                 for ( i = 0; attrs[ i ] != NULL; ++i ) {
632                                         printf( "%s ", attrs[ i ] );
633                                 }
634                         }
635                         printf( "\n#\n\n" );
636                 }
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, matches;
676         LDAPMessage             *res, *e;
677
678         if( filtpatt != NULL ) {
679                 sprintf( filter, filtpatt, value );
680
681                 if ( verbose ) {
682                         fprintf( stderr, "filter is: (%s)\n", filter );
683                 }
684
685                 if( ldif == 1 ) {
686                         printf( "#\n# filter: %s\n#\n", filter );
687                 }
688
689         } else {
690                 sprintf( filter, "%s", value );
691         }
692
693         if ( not ) {
694                 return( LDAP_SUCCESS );
695         }
696
697         if ( ldap_search( ld, base, scope, filter, attrs, attrsonly ) == -1 ) {
698                 int ld_errno;
699                 ldap_perror( ld, "ldap_search" );
700
701                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ld_errno);
702                 return( ld_errno );
703         }
704
705         matches = 0;
706         first = 1;
707         res = NULL;
708         while ( (rc = ldap_result( ld, LDAP_RES_ANY, sortattr ? 1 : 0, NULL, &res ))
709                 == LDAP_RES_SEARCH_ENTRY ) {
710         matches++;
711         e = ldap_first_entry( ld, res );
712         if ( !first ) {
713                 putchar( '\n' );
714         } else {
715                 first = 0;
716         }
717         print_entry( ld, e, attrsonly );
718         ldap_msgfree( res );
719         res = NULL;
720         }
721         if ( rc == -1 ) {
722         ldap_perror( ld, "ldap_result" );
723         return( rc );
724         }
725         if (( rc = ldap_result2error( ld, res, 0 )) != LDAP_SUCCESS ) {
726                 ldap_perror( ld, "ldap_search" );
727         }
728         if ( sortattr != NULL ) {
729                 (void) ldap_sort_entries( ld, &res,
730                         ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
731                 matches = 0;
732                 first = 1;
733                 for ( e = ldap_first_entry( ld, res ); e != NULL;
734                         e = ldap_next_entry( ld, e ) ) {
735                 matches++;
736                 if ( !first ) {
737                         putchar( '\n' );
738                 } else {
739                         first = 0;
740                 }
741                 print_entry( ld, e, attrsonly );
742                 }
743         }
744
745         if ( verbose ) {
746                 printf( "%d matches\n", matches );
747         }
748
749         ldap_msgfree( res );
750         return( rc );
751 }
752
753
754 static void
755 print_entry(
756         LDAP    *ld,
757         LDAPMessage     *entry,
758         int             attrsonly)
759 {
760         char            *a, *dn, *ufn;
761         char    tmpfname[ 256 ];
762         char    url[ 256 ];
763         int                     i;
764         BerElement              *ber = NULL;
765         struct berval   **bvals;
766         FILE            *tmpfp;
767
768         dn = ldap_get_dn( ld, entry );
769         ufn = NULL;
770
771         if ( ldif == 1 ) {
772                 ufn = ldap_dn2ufn( dn );
773                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, strlen( ufn ));
774         }
775         if ( ldif ) {
776                 write_ldif( LDIF_PUT_VALUE, "dn", dn, strlen( dn ));
777         } else {
778                 printf( "%s\n", dn );
779         }
780
781         if ( includeufn ) {
782                 if( ufn == NULL ) {
783                         ufn = ldap_dn2ufn( dn );
784                 }
785                 if ( ldif ) {
786                         write_ldif( LDIF_PUT_VALUE, "ufn", ufn, strlen( ufn ));
787                 } else {
788                         printf( "%s\n", ufn );
789                 }
790         }
791
792         if( ufn != NULL ) ldap_memfree( ufn );
793         ldap_memfree( dn );
794
795         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
796                 a = ldap_next_attribute( ld, entry, ber ) )
797         {
798                 if ( skipsortattr && strcasecmp( a, sortattr ) == 0 ) {
799                         continue;
800                 }
801
802                 if ( attrsonly ) {
803                         if ( ldif ) {
804                                 write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
805                         } else {
806                                 printf( "%s\n", a );
807                         }
808
809                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
810                         for ( i = 0; bvals[i] != NULL; i++ ) {
811                                 if ( vals2tmp > 1 || ( vals2tmp
812                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
813                                 {
814                                         int tmpfd;
815                                         /* write value to file */
816                                         sprintf( tmpfname, "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
817                                                 tmpdir, a );
818                                         tmpfp = NULL;
819
820                                         if ( mktemp( tmpfname ) == NULL ) {
821                                                 perror( tmpfname );
822                                                 continue;
823                                         }
824
825                                         if (( tmpfd = open( tmpfname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) == -1 ) {
826                                                 perror( tmpfname );
827                                                 continue;
828                                         }
829
830                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
831                                                 perror( tmpfname );
832                                                 continue;
833                                         }
834
835                                         if ( fwrite( bvals[ i ]->bv_val,
836                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
837                                         {
838                                                 perror( tmpfname );
839                                                 fclose( tmpfp );
840                                                 continue;
841                                         }
842
843                                         fclose( tmpfp );
844
845                                         sprintf( url, "%s%s", urlpre,
846                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
847
848                                         if ( ldif ) {
849                                                 write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
850                                         } else {
851                                                 printf( "%s%s%s\n", a, sep, url );
852                                         }
853
854
855                                 } else {
856                                         if ( ldif ) {
857                                                 write_ldif( LDIF_PUT_VALUE, a,
858                                                         bvals[ i ]->bv_val, bvals[ i ]->bv_len );
859
860                                         } else {
861                                                 int notprint = !binary && !vals2tmp
862                                                         && ldif_is_not_printable( bvals[i]->bv_val,
863                                                                 bvals[i]->bv_len ); 
864                                                 printf( "%s%s", a, sep );
865                                                 puts( notprint ? "NOT PRINTABLE" : bvals[ i ]->bv_val );
866                                         }
867                                 }
868                         }
869                         ber_bvecfree( bvals );
870                 }
871         }
872
873         if( ber != NULL ) {
874                 ber_free( ber, 0 );
875         }
876 }
877
878
879 static int
880 write_ldif( int type, char *name, char *value, ber_len_t vallen )
881 {
882         char    *ldif;
883
884         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
885                 return( -1 );
886         }
887
888         fputs( ldif, stdout );
889         ber_memfree( ldif );
890
891         return( 0 );
892 }