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